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

Slides:



Advertisements
Similar presentations
Overriding CMPS Overriding Recall, a method in a child class overrides a method in the parent class, if it has the same name and type signature.
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
CSE 1302 Lecture 8 Inheritance Richard Gesick Figures from Deitel, “Visual C#”, Pearson.
Inheritance Inheritance Reserved word protected Reserved word super
Object Oriented Programming Chapter 7 Programming Languages by Ravi Sethi.
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
C8: Understanding Inheritance. Intuitive description Intuitive: FLORISTS are SHOPKEEPERS, inheriting various shopkeeper behaviors Tension in OOP languages:
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Chapter 10 Classes Continued
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Inheritance and Polymorphism CS351 – Programming Paradigms.
CSCI-383 Object-Oriented Programming & Design Lecture 15.
CSSE501 Object-Oriented Development
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Programming Languages and Paradigms Object-Oriented Programming.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Peyman Dodangeh Sharif University of Technology Fall 2014.
Object Oriented Software Development
Programming Paradigms Lecturer Hamza Azeem. What is PP ? Revision of Programming concepts learned in CPLB Learning how to perform “Object-Oriented Programming”
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
(1) ICS 313: Programming Language Theory Chapter 12: Object Oriented Programming.
OOPs Object oriented programming. Abstract data types  Representationof type and operations in a single unit  Available for other units to create variables.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Java Inheritance in Java. Inheritance Inheritance is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
L 3.1 Forms of Inheritance Inheritance is used in a variety of way and for a variety of different purposes. Inheritance for Specialization Inheritance.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
CSCI 383 Object-Oriented Programming & Design Lecture 15 Martin van Bommel.
Polymorphic Variables CMPS2143. The Polymorphic Variable A polymorphic variable is a variable that can reference more than one type of object (that is,
Modern Programming Tools And Techniques-I
Object-Oriented Programming Concepts
7.1 What Is An Object Object-oriented program - Description or simulation of application Object-oriented programming is done by adopting or extending an.
Inheritance and Polymorphism
Object Oriented Programming in Java
Road Map Inheritance Class hierarchy Overriding methods Constructors
Lecture 22 Inheritance Richard Gesick.
Object-Oriented PHP (1)
Presentation transcript:

Inheritance CMPS 2143

Overview Stream classes File objects File operations with streams Examples in C++ and Java 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 stucture 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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() {…} };

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

UML diagram for public interface D extends A, B 27

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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