460 likes | 537 Views
Inheritance. CMPS 2143. Overview. Stream classes File objects File operations with streams Examples in C++ and Java. Learning OOP. Requires learning how to organize interaction of loosely coupled software components Requires learning how to organize classes into a hierarchical stucture.
E N D
Inheritance CMPS 2143
Overview • Stream classes • File objects • File operations with streams • Examples in C++ and Java
Learning OOP • Requires learning how to organize interaction of loosely coupled software components • Requires learning how to organize classes into a hierarchical stucture
Inheritance Property that instances of a child class (subclass, derived class) can access both data and behavior (methods) associated with a parent class (superclass).
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
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
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.
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.
Reasons to use Inheritance • REUSE CODE • REUSE CONCEPTS
Code reuse • Do NOT rewrite code for a child class that is identicalto code in the parent class!!!
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
Example class Shape { public: virtual void getArea ( ) const { boring or nonexistant code; } }; class Square : Shape const { public: virtual double getArea() { return Math.pow (length, 2); } };
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!!!
Example: Class parent { private: int three; protected: int two; public: int one; Parent ( ) {one=two=three= 42;} //other methods };
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.
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.
Other languages syntax • C++ class Square : public Shape {…}; • C# class Square : Shape { ….} • Java class Square extends Shape { …} • Python class Square (Shape): def__init__ (self): : • Ruby class Square < Shape : end
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
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.)
Example of Subtype (C++) //assume you have a linked list of shapes Shape * sptr = shapesList; while (sptr != null) { (sptr->shape).draw(); sptr = sptr->next; } shape next null sptr circle oval circle
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)
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 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
Override syntax • Smalltalk and Java – 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 (virtual, override…) • Parent class gives permission using keyword • Child class indicates they are indeed doing so • Or both
Example Java class Shape { public void draw () { : } } class Circle : Shape { public void draw () () { : } }
Example C++ .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() {…} };
Interfaces • Chap 4 concept: Interface • Interfaces can inherit from other interfaces (even multiple parent interfaces) • Java examples public interface IHockey extends ISports, IEvent public interface ISpork extends IFork, Ispoon public interface GroupIntfc extends Intfc1, Intfc2, Intfc3 • Class can inherit from another class, while also implementing an interface. public class Clock extends Applet implements Runnable
Abstract Classes • Midway between interfaces and classes • A class can define one or more methods as abstract • No body in an abstract method • Child class MUST implement it (if child class is not abstract) • So parent class specifies behavior, but child class implements it • If a class has an abstract method, the class is itself abstract • A class may be abstract, even if no methods are abstract • Means you can’t instantiate it
Examples (Java) abstract class Window { : //draw contents of window abstract public void paint (); : }
Examples (C++) class Window { public: : //draw contents of window virtual void paint () = 0; //pure virtual : };
More on abstract classes • A class can have both abstract (or pure virtual) methods and non-abstract methods. • If all methods are abstract (or pure virtual) …it corresponds to an interface
Forms of Inheritance • Subclassing for specialization (subtyping) • Subclassing for specification • Subclassing for construction • Subclassing for generalization • Subclassing for extension • Subclassing for limitation • Subclassing for variance • Subclassing for combination
Forms of Inheritance • Specialization (subtyping) • Child class is special case of parent (subtype) • textWindow is a Window - move, resize, iconify, etc. + displays textual material • Specification • Parent class specifies behavior that child implements • Parent class has abstract method(s) • Rectangle is a shape (getArea?) • Construction • Child class makes use of behavior provided by parent, but is not a subtype (breaks the principle of substitution) • Circle inherits Point methods (but a Circle is-not-a Point)
Forms of Inheritance • Generalization • Child class adds additional fields • ColoredWindow is a Window (adds a background color) • However, a Window is a ColoredWindow (bkcolor is white) • Extension • Child class adds new functionality, but does not change any inherited behavior • Limitation • Child class restricts the use of some of the behavior inherited from the parent • Child class Queue, parent class Deque • Child class Stack, parent class Deque
Forms of Inheritance • Variance • Child class and parent class are variants of each other, and the class-subclass relationship is arbitrary • Code to control mouse similar to graphics tablet • One or other is arbitrarily chosen to be parent • BETTER: Factor out common code to an abstract PointingDevice class • Combination • Child class inherits features from more than one parent class multiple inheritance • TeachingAssistant is a Teacher and a Student
Variations on Inheritance • Java anonymous classes • Inheritance and constructors • Virtual destructors
Java anonymous classes • A simple class, will only be one instance of it (singleton) • Frequently arises in user interfaces • Example: Create a new class that inherits from ButtonAdapter and override method add (inline) and add the button to the window p. Window p = …; p.add (new ButtonAdapter (“Quit”) { public void pressed () {System.exit(0);} } );
Inheritance and constructors • Inheritance complicates construction • Both parent and new child class may have initialization to perform • Java and C++ and C# - both will be executed as long as parent does not require additional parameters • If parent does, child must supply them
Virtual Destructors • A method invoked to recover memory and other resources allocated • If substitution and overriding are anticipated, then destructor should be declared virtual • Remember parent constructor may have dynamically allocated memory for data members inherited
Java example class Employee { public Employee (String n, double s) { name = n; salary = s; : private String name; private double salary; } class Manager extends Employee { public Manager (String n, double s, double b) { super (n, s); //do not have access to name bonus = b; } : private double bonus; }
C++ example class Employee { public: Employee (String n, double s) { name = n; salary = s; : private: string name; double salary; } class Manager : Employee { public: Manager (String n, double s, double b): Employee (n, s){ bonus = b; } : private double bonus; };
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
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.
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
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)