29
I NHERITANCE AND S UBSTITUTION Muhammad Adil Raja Roaming Researchers, Inc. cbna April 17, 2015

Inheritance and Substitution

Embed Size (px)

Citation preview

INHERITANCE AND SUBSTITUTION

Muhammad Adil Raja

Roaming Researchers, Inc.

cbna

April 17, 2015

OUTLINE I

INTRODUCTION

A FEW IDEAS

SUBSTITUTION

FORMS OF INHERITANCE

REFERENCES

INTRODUCTION I

I In this chapter we will start to investigate the concepts ofinheritance and substitution.

I The intuitive and practical meanings of inheritance.I The syntax used to describe inheritance and substitution.I Some of the various forms of inheritance.I The benefits and costs of inheritance.

ABSTRACT IDEA OF INHERITANCE

FIGURE : An Abstract Inheritance Tree

PRACTICAL MEANING OF INHERITANCE I

MESSAGE SYNTAX

I Data members in the parent are part of the childI Behavior defined in the parent are part of the childI Note that private aspects of the parent are part of the child,

but are not accessible within the child class.

PRIVATE, PUBLIC AND PROTECTED I

I There are now three levels of visibility modifiers:I private: accessible only within the class definition (but

memory is still found in the child class, just not accessible).I public: accessible anywhereI protected: accessible within the class definition or within

the definition of child classes.I Note: Java interprets protected to mean accessible within

same package

INHERITANCE IS BOTH EXTENSION AND CONTRACTION

I

I Because the behavior of a child class is strictly larger thanthe behavior of the parent, the child is an extension of theparent. (larger)

I Because the child can override behavior to make it fit aspecialized situation, the child is a contraction of theparent. (smaller)

I This interplay between inheritance and overriding,extension and contraction, is what allows object-orientedsystems to take very general tools and specialize them forspecific projects.

I This interplay is ultimately the source of a great deal of thepower of OOP.

THE IS-A RULE

I Our idealization of inheritance is captured in a simplerule-of-thumb.

I Try forming the English sentences “An A is-a B”. If it“sounds right” to your ear, then A can be made a subclassof B.

I A dog is-a mammal, and therefore a dog inherits frommammal

I A car is-a engine sounds wrong, and therefore inheritanceis not natual. but a car has-a engine.

REUSE OF CODE – REUSE OF CONCEPT

I Why do we use inheritance?I Basically there are two major motivations:I Reuse of code.I Methods defined in the parent can be made available to

the child without rewriting. Makes it easy to create newabstractions.

I Reuse of concept.I Methods described in the parent can be redefined and

overridden in the child.I Although no code is shared between parent and child, the

concept embodied in the definition is shared.I An example of the latter from the case study in chapter 7,

all graphical objects know how to draw.

SYNTAX FOR INHERITANCE

Languages use a variety of different syntax to indicateinheritance:

SYNTAX OF ABSTRATION IN VARIOUS LANGUAGES

class Wall : public Graphica lObject −− c++

class Wall extends Graphica lObject −− Java

class Wall : Graph ica lObjec t −− C#

( de fc lass Wall ( Graphica lObject ) ( ) ) −− CLOS

type Wall = ob jec t ( Graph ica lObjec t ) −− Object Pascal

class Wall < Graphica lObjec t −− Ruby

TREES VS FORESTS

I There are two common views of class hierarchies:I All classes are part of a single large class hierarchy.I Thus, there is one class that is the original ancestor of all

other classes.I Smalltalk, Java and Delphi Pascal do this.I Classes are only placed in hierarchies if they have a

relationship - results in a forest of many small hierarchies,but no single ancestor.

I C++, Objective-C, and Apple Object Pascal do this.

ON SUBSTITUTION

I Consider the following argument:I Instances of the subclass must possess all data areas

associated with the parent class.I Instances of the subclass must implement, through

inheritance at least (if not explicitly overridden) allfunctionality defined for the parent class.

I (They can also define new functionality, but that isunimportant for the present argument).

I Thus, an instance of a child class can mimic the behaviorof the parent class.

I It therefore seems reasonable that a variable declared as aparent, should be able to hold a value generated from thechild class.

SUBCLASS VS SUBTYPE

I Of course, the problem with this argument is that a childclass can override a method and make arbitrary changes.

I It is therefore useful to define two separate concepts:I To say that A is a subclass of B merely asserts that A is

formed using inheritance.I To say that a is a subtype of B asserts that A preserves the

meaning of all the operations in B.I It is possible to form subclasses that are not subtypes; and

(in some languages at least) form subtypes that are notsubclasses.

SYNTAX FOR OVERRIDING

SYNTAX FOR OVERRIDINGSome languages, such as C++, require that the programmerindicate in the parent class that overriding is a potential:class Graphica lObject {

public :v i r t u a l void draw ( ) ; / / can be over r idden

} ;

Other languages, such as Object Pascal, require a modifier inthe child class that overriding has taken place:type

B a l l = ob jec t ( Graphica lObject ). . .procedure draw ; ove r r i de ; (∗ o v e r r i d i n g has taken place ∗)

end

Still other languages (C#, Delphi) require indications in bothparent and child. And some languages (Smalltalk) do notrequire any indication in either parent class or child class.

INTERFACES AND ABSTRACT CLASSES

I An interface is similar to a class, but does not provide anyimplementation.

I A child class must override all methods. A middle ground isan abstract class.

I Here some methods are defined, and some (abstractmethods) are undefined.

I A child class must fill in the definition for abstract methods:

SOME CODE

abstract class Window {. . .abstract public void p a i n t ( ) ; / / c h i l d c lass must rede f i ne. . .

}

I An interface is like an abstract class in which all methodsare abstract.

I In C++ an abstract method is called a pure virtual method.

FORMA OF INHERITANCE

I The choices between inheritance and overriding, subclassand subtypes, mean that inheritance can be used in avariety of different ways and for different purposes.

I Many of these types of inheritance are given their ownspecial names.

I We will describe some of these specialized forms ofinheritance.

I Specialization.I Specification.I Construction.I Generalization or Extension.I Limitation.I Variance.

SPECIALIZATION INHERITANCE I

I By far the most common form of inheritance is forspecialization.

I A good example is the Java hierarchy of Graphicalcomponents in the AWT:

I Component.I Label.I Button.I TextComponent.

I TextArea.I TextField.

I CheckBox.I ScrollBar.

I Each child class overrides a method inherited from theparent in order to specialize the class in some way.

SPECIFICATION INHERITANCE

I If the parent class is abstract, we often say that it isproviding a specification for the child class, and therefore itis specification inheritance (a variety of specializationinheritance).

I Example: Java Event Listeners.I ActionListener, MouseListener, and so on specify behavior,

but must be subclassed.

INHERITANCE FOR CONSTRUCTION

I If the parent class is used as a source for behavior, but thechild class has no is-a relationship to the parent, then wesay the child class is using inheritance for construction.

I An example might be subclassing the idea of a Set from anexisting List class.

I Generally not a good idea, since it can break the principleof substituability, but nevertheless sometimes found inpractice. (More often in dynamically typed languages, suchas Smalltalk).

INHERITANCE FOR GENERALIZATION OR EXTENSION

I If a child class generalizes or extends the parent class byproviding more functionality, but does not override anymethod, we call it inheritance for generalization.

I The child class doesn’t change anything inherited from theparent, it simply adds new features.

I An example is Java Properties inheriting form Hashtable.

INHERITANCE FOR LIMITATION

I If a child class overrides a method inherited from theparent in a way that makes it unusable (for example, issuesan error message), then we call it inheritance for limitation.

I For example, you have an existing List data type thatallows items to be inserted at either end, and you overridemethods allowing insertion at one end in order to create aStack.

I Generally not a good idea, since it breaks the idea ofsubstitution.

I But again, it is sometimes found in practice.

INHERITANCE FOR VARIANCE

I Two or more classes that seem to be related, but its notclear who should be the parent and who should be thechild.

I Example: Mouse and TouchPad and JoyStick.I Better solution, abstract out common parts to new parent

class, and use subclassing for specialization.

SUMMARY OF FORMS OF INHERITANCE I

SPECIALIZATION: The child class is a special case of the parentclass; in other words, the child class is a subtypeof the parent class.

SPECIFICATION: The parent class defines behavior that isimplemented in the child class but not in theparent class.

CONSTRUCTION: The child class makes use of the behaviorprovided by the parent class, but is not a subtypeof the parent class.

GENERALIZATION: The child class modifies or overrides someof the methods of the parent class.

EXTENSION: The child class adds new functionality to theparent class, but does not change any inheritedbehavior.

SUMMARY OF FORMS OF INHERITANCE II

LIMITATION: The child class restricts the use of some of thebehavior inherited from the parent class.

VARIANCE: The child class and parent class are variants ofeach other, and the class-subclass relationship isarbitrary.

COMBINATION: The child class inherits features from more thanone parent class. This is multiple inheritance andwill be the subject of a later chapter.

BENEFITS OF INHERITANCE

I Software Reuse.I Code Sharing.I Improved Reliability.I Consistency of Interface.I Rapid Prototyping.I Polymorphism.I Information Hiding.

COST OF INHERITANCE

I Execution speed.I Program size.I Message Passing Overhead.I Program Complexity.I This does not mean you should not use inheritance, but

rather than you must understand the benefits, and weighthe benefits against the costs.

SUMMARY

I In this chapter we have begun the exploration ofinheritance, a topic we will continue through the nextseveral chapters.

I Topics we have addressed have included the following:I The meaning of inheritance.I The syntax used to describe inheritance and overriding.I The idea of substitution of a child class for a parent.I The various forms of inheritance.I The cost and benefits of inheritance.

REFERENCES I

I Images and content for developing these slides have beentaken from the follwoing book with the permission of theauthor.

I An Introduction to Object Oriented Programming, TimothyBudd.

I This presentation is developed using Beamer:I Berlin, monarca.