19
Agenda Abstraction Abstract class Formal definition Example When to use abstract class Interface Formal definition Example When to use interface Difference between abstract class and interface

Abstract class and Interface

Embed Size (px)

Citation preview

Agenda

• Abstraction

• Abstract class– Formal definition– Example– When to use abstract class

• Interface– Formal definition– Example– When to use interface

• Difference between abstract class and interface

Abstraction

• Abstraction is a process by which concepts are derived from the usage and classification of literal ("real" or "concrete") concepts.

• Abstraction is a concept that acts as a super-categorical noun for all subordinate concepts, and connects any related concepts as a group, field, or category.

• Abstractions may be formed by reducing the information content of a concept or an observable phenomenon, typically to retain only information which is relevant for a particular purpose.

• For example, abstracting a leather soccer ball to the more general idea of a ball retains only the information on general ball attributes and behavior, eliminating the other characteristics of that particular ball.

AbstractionExample

Vehicle

Box truck

Sports car Sedan car

Pickup truck

• Here we have different types of truck and car. They have different color, shape, engine type and purpose etc. that makes them distinct.

• But they have some common properties and behavior among them i.e. they all have tires, engine, steering, gear etc. They are used for the travelling and can be operated in a common way.

• What should be the abstract concept for these entities?

• Vehicle can be the general idea of a car or a truck. It retains only the information on general vehicle attributes and behavior, eliminating the other characteristics of a particular car or a truck.

AbstractionExample

Sedan carSports car

Car

Classic truckBox truck

Truck

Vehicle

• Here we have four classes Box truck, Classic truck, Sports car and Sedan car.

• We can categorize them into two major categories Truck and Car and can make abstract classes which will contain all the common properties and behaviors for trucks and cars.

• We can further introduce abstraction for the Truck and Car categories by adding a new abstract class Vehicle that will hold common properties and behaviors for its inheriting classes.

AbstractionExample

Dog Tiger Horse

Animal

• Animal can be the abstraction for a dog, tiger, horse etc. It acts as a super-categorical noun.

• As an abstract concept it can hold all the common properties and behaviors present in different species

AbstractionExample

Animal

color : Stringpattern : String

sound()eat()run()

Horse

sound()

Tiger

sound()attack()

Dog

sound()guard()

• Here we have the abstract class Animal. We have defined color and pattern properties and sound, eat and run behaviors which are present in all animals.

• The behaviors/ methods can be abstract and the implementation can be provided in the inheriting classes.

• Now we have three concrete classes inheriting from the Animal class. Overriding the sound behavior and adding some behaviors specific to the entities.

AbstractionExample

Aircraft

Propeller plane Fighter plane Passenger plane

• Aircraft can be the abstraction for a Propeller plane, Fighter plane, Passenger plane etc. It acts as a super-categorical noun.

• As an abstract concept it can hold all the common properties and behaviors present in different aircrafts.

AbstractionExample

Aircraft

color : Stringengine : Object

start()stop()takeOff()land()

Passenger planeFighter planePropeller plane

start()stop()takeOff()land()

• Here we have the abstract class Aircraft. We have defined color and engine properties and start, stop takeOff and land behaviors which are present in all Aircrafts.

• Now we have three concrete classes inheriting from the Aircraft abstract class. We have added some more properties and behaviors specific to the entities.

• For example in Propeller plane the number of propellers, in Fighter plane the weapon and the fire behavior.

propellers : int

start()stop()takeOff()land()fire()

weapon : Object passengers : int

start()stop()takeOff()land()

Abstract class

• Abstract classes are special classes defined with the keyword abstract.

• Abstract class is a concept and implementation gets completed when it is being realized by a subclass.

• Abstract classes provide elements of both inheritance and interfaces.

• An abstract class is a class that cannot be instantiated itself; it must be inherited.

• Some or all members of the class might be unimplemented, and it is up to the inheriting class to provide that implementation.

• Members that are implemented might still be overridden, and the inheriting class can still implement additional interfaces or other functionality.

Abstract classExample

Bank Account

owner : Stringbalance : Dollar

deposit(amount : Dollar)withdraw(amount : Dollar)

Checking Account

owner : Stringbalance : Dollar

deposit(amount : Dollar)

insufficientFundsFee : Dollar

processCheck(checkToProcess : Check)withdraw(amount : Dollar)

Saving Account

owner : Stringbalance : Dollar

deposit(amount : Dollar)

annualInterestRate : Percentage

depositMonthlyInterest()withdraw(amount : Dollar)

• Here we have two classes Checking Account and Saving Account.

• What are the common properties and behavior between them? And what can be the abstract class for these entities?

When to use abstract class?• Abstract class provides a template for future specific classes.

• Use an abstract class to provide default behaviors (Code reusability).

• Abstract class defines common interface for its subclasses.

• Abstract operations (methods) can be declared and their implementation can be provided later in the concrete classes.

• Abstract classes are useful when creating components because they allow us to specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed.

• When creating a class library which will be widely distributed or reused especially to clients, use an abstract class in preference to an interface; because it simplifies versioning. This is the practice used by the Microsoft team which developed the Base Class Library.

Interface

• Every method declared by an object specifies the method's name, the object/value it takes as parameters, and the method's return value. This is known as the operation signature.

• The set of all signatures defined by an object's methods is called the interface to the object. An object's interface characterizes the complete set of requests that can be sent to the object.

• An interface is like an abstract class that cannot be instantiated. Interfaces are better suited to situations in which your applications require many possibly unrelated object types to provide certain functionality.

• Explicitly implementing interface in a class enables us to define a set of methods that are mandatory for that class.

• Interface definition begins with the keyword interface.

InterfaceExample

Mammals

• These are all mammals and share some common behavior and properties. Like they are warm blooded, they can have fur or hair, they nourish their young with milk etc.

• Bat has a special behavior i.e. that it can fly. Flying is the behavior which is only available in Bat and not in other mammal.

• Birds can also fly.

• The Bat and Bird belongs to two different categories but they have a common flying behavior between them.

• In this scenario we can create an IFlyable interface and make the Bat and Bird class implement this interface.

Can fly

Birds

InterfaceExample

• Fountain pen and ball point pen are used for writings, they are related entities. What should be the abstract class for these entities?

• We can write using pen but we can also write with charcoal. Over here what is the common behavior between pen and charcoal that can be abstracted?

Ball point pen

draw()

Fountain pen

draw()refill()

Charcoal

burn()draw()

Pen

color : Stringdraw()

<<IWritable>>

draw()

Person

write(IWritable : instrument)

InterfaceExample: IDisposible Interface in .Net

• Several objects in .Net implement IDisposible interface to free managed and unmanaged resources. using statement expects IDisposible interface and calls the Dispose method as soon as the statement ends.

• If an object does not implements IDisposible interface and is used in the using statement, the compiler throws error.

When to use Interface?

• Use an interface when an immutable contract is really intended.

• Interfaces are better suited in situations when your applications require many possibly unrelated object types to provide certain functionality.

• Interfaces are better in situations in which you do not need to inherit implementation from a base class.

• Interfaces can be used for multiple inheritance.

Difference between abstract class and interfaceFeature Interface Abstract class

Multiple Inheritance A class may implement several interfaces.

A class may inherit only one abstract class.

Default implementation An interface is purely abstract, it cannot provide any code, just the signature.

An abstract class can provide complete, default code and/or just the details that have to be overridden.

Access modifiers An interface cannot have access modifiers for the method, properties etc. Everything is assumed as public.

An abstract class can contain access modifiers for the methods, properties etc.

Core vs. Peripheral Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.

An abstract class defines the core identity of a class and there it is used for related objects.

Homogeneity If various implementations only share method signatures then it is better to use Interfaces.

If various implementations are of the same kind and use common behavior or status then abstract class is better to use.

Difference between abstract class and interfaceFeature Interface Abstract class

Adding functionality (Versioning)

If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constants defined

Is-a, can-do analogy

• Abstract classes are classes that can be purely abstract.

• It serves as a base for other classes. When a class is derived from a base class, that derived class has an "is-a" relationship with the base.

• For example an Employee is a person and a Triangle is a shape so these cases could easily justify a base class and “is-a” relationship.

• Interfaces are purely abstract and guarantee member invariance. They represent "can-do" or an invariant contract that specifies "can do and will always do as expected to do“.

• Its appropriate to use an interface when it will be used by many, unrelated types or in situations when multiple inheritance is required.