Objects and Classes Abstract Classes and Interface Sanjaya Karunasena
Outline Abstract Classes and abstract methods Interface Classes
Abstract Classes Some times in a inheritance hierarchy, having a instance of a super (parent) class does not make sense Instance of the class Pet does not make sense when there are sub classes like, Dog, Cat, etc. However we still need the super class to have generalization We can achieve this by making the super class abstract Instance of an abstract class cannot be created Abstract class can be used to enforce some behavior to the sub class This is achieved by declaring abstract methods
Abstract Classes cont. An abstract method doesn’t have an implementation Sub classes have to implement the parent’s abstract methods In most of the programming languages if a class to be abstract it need to have at least one abstract method Pet CatDog + Talk()
Abstract Classes cont.
Interface Classes Some times we would like to enforce some behavior across unrelated classes In other words classes may have similar behavior even though they don’t belong to the same parent We can enforce such behavior by making use of an interface class Interface class can only have abstract methods It can have attributes To obtain the behavior defined by an interface, a class has to implement the interface class
Interface Classes cont. There could be generalization within interfaces A class can implement multiple interfaces When unrelated classes implement the same interface they will have some sort of similar behavior even though they are not related at all
Interface Classes cont. CatDogCar VehiclePet Lorry IRace_able
Interface Classes cont.
References The Unified Modeling Language User Guide – Grady Booch, James Rumbaugh, Ivar Jacobson UML™2 Bible – Tom Pender