Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inheritance CMPS 2143. Overview Stream classes File objects File operations with streams Examples in C++ and Java 2.

Similar presentations


Presentation on theme: "Inheritance CMPS 2143. Overview Stream classes File objects File operations with streams Examples in C++ and Java 2."— Presentation transcript:

1 Inheritance CMPS 2143

2 Overview Stream classes File objects File operations with streams Examples in C++ and Java 2

3 Learning OOP 1.Requires learning how to organize interaction of loosely coupled software components 2.Requires learning how to organize classes into a hierarchical stucture 3

4 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

5 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

6 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

7 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

8 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

9 Reasons to use Inheritance 1. REUSE CODE 2.REUSE CONCEPTS 9

10 Code reuse Do NOT rewrite code for a child class that is identical to code in the parent class!!! 10

11 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

12 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); } }; 12

13 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

14 Example: Class parent { private: int three; protected: int two; public: int one; Parent ( ) {one=two=three= 42;} //other methods }; 14

15 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. 15

16 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. 16

17 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 17

18 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 18

19 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.) 19

20 Example of Subtype (C++) //assume you have a linked list of shapes Shape * sptr = shapesList; while (sptr != null) { (sptr->shape).draw(); sptr = sptr->next; } 20 sptr null circle oval shape next

21 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) 21

22 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 22

23 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 23

24 Example Java class Shape { public void draw () { : } class Circle : Shape { public void draw () () { : } 24

25 Example C++.h fileC# 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 () { : } 25 C++.cpp file virtual void Shape:: draw() {…} };

26 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 26

27 UML diagram for public interface D extends A, B 27

28 UML diagram for public class D extends C implements A, B 28

29 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 29

30 Examples (Java) abstract class Window { : //draw contents of window abstract public void paint (); : } 30

31 Examples (C++) class Window { public: : //draw contents of window virtual void paint () = 0; //pure virtual : }; 31

32 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 32

33 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 33

34 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) 34

35 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 35

36 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 36

37 Variations on Inheritance Java anonymous classes Inheritance and constructors Virtual destructors 37

38 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);} } ); 38

39 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 39

40 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 40

41 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; } 41

42 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; }; 42

43 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 43

44 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. 44

45 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 45

46 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) 46


Download ppt "Inheritance CMPS 2143. Overview Stream classes File objects File operations with streams Examples in C++ and Java 2."

Similar presentations


Ads by Google