Inheritance
CMPS 2143
2
Learning OOP
1. Requires learning how to organize interaction of loosely coupled software components
2. Requires learning how to organize classes into a hierarchical structure
3
Inheritance
Property that instances of a child class (subclass, derived class) can access both data and behavior (methods) associated with a parent class (superclass).
4
Intuitive example
•Fred (the Florist)▫Exhibits all the behaviors of a florist
e.g., arranges flower, delivers them▫BUT Fred is also a shopkeeper
Request money for transactions, gives receipts, etc.
•Florist is a specialized form of a Shopkeeper
5
Inheritance
•Behavior and data associated with a child class are an extension of the properties of a parent class
•A subclass▫Has all the properties of the parent class▫+ expanded additional properties ▫BUT since it is specialized, may also be a restricted form
Example: A Stack is a List, but it only has LIFO access
6
The is-a test
•Rule of thumb only▫A florist is a shopkeeper.▫A double room is a hotel room.▫A square is a rectangle.▫A rectangle is a parallelogram.▫A bird is NOT a mammal.▫An apple pie is not an apple.
•Sometimes inheritance is used when the is-a test fails, but not usually.
7
Inheritance is transitive.
•A dog is a mammal.•A mammal is an animal.• A dog is an animal.
•An freshman is an undergraduate.•An undergraduate is a student.• A freshman is a student.
8
Reasons to use Inheritance
1. REUSE CODE
2. REUSE CONCEPTS
9
Code reuse
•Do NOT rewrite code for a child class that is identical to code in the parent class!!!
10
Concept reuse
•Do NOT declare/define a new method for a child class for the same behavior
OVERRIDE it.Change the implementation!
•NO code is shared, although child and parent share the behavior
11
C++ Exampleclass Shape { public: virtual void getArea ( ) const { boring or nonexistant code; }};
class Square : public Shape { public: virtual double getArea() const { return Math.pow (length, 2); }};
12
protected access modifier
•Allows child classes to access the member data directly
•BUT, if parent class implemented a different way, you will have to re-write child classes as well.
• I SUGGEST NEVER using protected!!!
13
C++ Example:class Parent { private: int three; protected: int two; public: int one; Parent ( ) {one=two=three= 42;} //other methods};
14
C++ Example:class Child: public Parent { public: void inChild() { one = 1; two = 2; //legal
three = 3; //illegal }};
15
C++ Example:void main (){ Child c; cout << c.one; //legal cout << c.two; //illegal cout << c.three; //illegal}
16
Inheritance in various Languages•Reminder: Java, C#, Smalltalk, Objective-C, and Delphi
Pascal require every class to inherit from an existing parent class.▫Object in Smalltalk,Objective-C, Java, C#▫TObject in Delphi Pascal
•C++ and Apple Pascal do NOT. ▫They support, but do NOT enforce OOP.▫Doesn’t mean we can do inheritance in these languages.
17
Insistence that all classes inherit from a class…
•Advantage: single root class that is an ancestor to all objects.▫Nice if we have an array of references to various types of
objects•Disadvantage: a SINGLE large inheritance tree
combining all classes into a tightly coupled unit.▫Languages that #include libraries have to bring everything
in.▫ another reason for import.
18
Other languages syntax•C++ class Square : public Shape {…};• Java class Square extends Shape { …}
•C# class Square : Shape { ….}•Python class Square (Shape): def __init__ (self): :•Ruby class Square < Shape : end
19
Subclass, Subtype, and Substitution
• Idealized view of subclasses▫Instances of child classes possess all data members
associated with the parent class▫Instances of child classes possess all functionality (that is,
methods) of the parent class▫Thus, a instance of a child class can mimic behavior of the
parent class AND is indistinguishable from an instance of a parent class if substituted in a similar situation.
•Not always valid, but when it is – it is said to support the principle of substitution
20
Principle of Substitution
• “If class B is a subclass of class A (perhaps several times removed), it should be possible to substitute instances of class B for instances of class A in any situation with no observable effect.”
•The term subtype is used to refer to a subclass that satisfies the principle of substitution (versus the more general term subclass which may or may not satisfy it.)
21
Example of Subtype (C++)//assume you have a linked list of shapesShape * sptr = shapesList;
while (sptr != null) { (sptr->shape).draw(); sptr = sptr->next;}
sptr nullcircle circle oval
shape next
22
Substitution and strong typing
•Statically typed languages (C++, Java, C#, Pascal) place more emphasis on principle of substitution than dynamically typed languages (Smalltalk, Perl, Obj-C).▫Statically typed languages characterize objects by their
class▫Dynamically typed languages characterize objects by their
behavior (so as long as the it can respond to the message, it is okay)
23
Overriding and Virtual Methods•Child classes might find it necessary to modify or
override the behavior they inherit from their parent class
•Means the child will have a method with the same name as one in the parent class (as well as signature), but the implementation will be different▫In this case we want to ignore the method from the
parent and execute the method in the child
24
Override syntax
• Java and Smalltalk – occurs naturally when a child class declares a method with the same name/signature
•C++ and C# require you be explicit, using keywords to designate this is permitted ▫C++ - virtual and C# - override▫Parent class gives permission using keyword▫Child class indicates they are indeed doing so▫Or both
25
ExampleC++ .h file C#
class Shape { public: virtual void draw ();};
class Circle : public Shape { public: virtual void draw (); };
class Shape { public: virtual void draw () { : }}
class Circle : Shape { public override void draw () { : }}
C++ .cpp file
virtual void Shape::draw() {…}};
26
ExampleJava - implicit
class Shape { public void draw () { : }}
class Circle extends Shape { public void draw () () { : }}
44
Benefits of Inheritance
•Software reusability –▫do not have to rewrite code that is inherited
•Code sharing▫Several classes can inherit from the same parent class
•Consistency of interface▫Inheriting methods means if one class understood, the
parent or child class will be too.•Software components▫Can create libraries for a collection of classes
45
Benefits of Inheritance
•Rapid Prototyping▫Focus on new/unusual portions of the system▫Reuse old/common/usual portions
•Polymorphism and Frameworks▫Easier to generate high-level reusable components
tailored to fit different applications by change low-level components
• Information Hiding▫Only need to understand nature of component and its
interface, so if super methods are called or overridden, client code need not worry about it.
46
Costs of Inheritance•Execution speed▫Run-time needs to figure out what method is actually
called▫BUT programmer time MORE expensive
•Program size ▫Reusing code means you might bring in more than what
you actually need▫BUT reusing code means less time debugging new code
47
Costs of Inheritance•Message-passing overhead▫Method call chaining▫May really only be a few more assembly instructions▫Total time penalty +10%
Higher in dynamically bound languages like Lisp•Program Complexity▫Overuse can be confusing▫Most people can deal with up to 3 levels
Have to do multiple up and down scans of code or inheritance graph (yo-yo problem)