Inheritance Type/Subtype Relationship. Inheritance Idea: An object B of one type, termed child class, inherits from another object A of another type,

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

Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Object Oriented Programming
CS 211 Inheritance AAA.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
C8: Understanding Inheritance. Intuitive description Intuitive: FLORISTS are SHOPKEEPERS, inheriting various shopkeeper behaviors Tension in OOP languages:
Inheritance and object compatibility Object type compatibility An instance of a subclass can be used instead of an instance of the superclass, but not.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Introduction to Inheritance Fall 2005 OOPD John Anthony.
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
Abstraction: Polymorphism, pt. 1 Abstracting Objects.
CSCI-383 Object-Oriented Programming & Design Lecture 15.
CSSE501 Object-Oriented Development
Subclasses and Subtypes CMPS Subclasses and Subtypes A class is a subclass if it has been built using inheritance. ▫ It says nothing about the meaning.
GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter.
Inheritance One of the biggest advantages of object-oriented design is that of inheritance. A class may be derived from another class, the base class.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Computer Science and Engineering College of Engineering The Ohio State University Lot More Inheritance and Intro to Design Patterns Lecture 12.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
1 COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
What is inheritance? It is the ability to create a new class from an existing class.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Effective C#, Chapter 1: C# Language Elements Last Updated: Fall 2011.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
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.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
CSI 3125, Preliminaries, page 1 Inheritance. CSI 3125, Preliminaries, page 2 Inheritance Using inheritance, can create a general class that defines traits.
Inheritance and Polymorphism
Java Inheritance 1/13/2015. Learning Objectives Understand how inheritance promotes software reusability Understand notions of superclasses and subclasses.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Polymorphism 1. Reuse of code: every time a new sub-class is defined, programmers are reusing the code in a super-class. All non-private members of a.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
1 Inheritance One of the goals of object oriented programming is code reuse. Inheritance is one mechanism for accomplishing code reuse. It allows us to.
CSCI 383 Object-Oriented Programming & Design Lecture 15 Martin van Bommel.
Modern Programming Tools And Techniques-I
Lecture 12 Inheritance.
Object-oriented Programming in Java
03/10/14 Inheritance-2.
Table of Contents Class Objects.
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Interfaces.
Chapter 9 Carrano Chapter 10 Small Java
CIS 199 Final Review.
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Topics OOP Review Inheritance Review Abstract Classes
Presentation transcript:

Inheritance Type/Subtype Relationship

Inheritance Idea: An object B of one type, termed child class, inherits from another object A of another type, termed parent class, if B can access the data and methods of A Idea: An object B of one type, termed child class, inherits from another object A of another type, termed parent class, if B can access the data and methods of A Loosely speaking, we can also say that the child class inherits from the parent class Loosely speaking, we can also say that the child class inherits from the parent class In Java every class inherits from the Object class, i.e. Object is parent to every class In Java every class inherits from the Object class, i.e. Object is parent to every class

The Class Object Extends any class, by definition Extends any class, by definition Has the general methods Has the general methods equals()-- meaning this and its parameter have the same content equals()-- meaning this and its parameter have the same content getClass()-- returns the class of the object that invokes it, e.g. getClass()-- returns the class of the object that invokes it, e.g. if (X.getClass()==IdTree.class)... if (X.getClass()==IdTree.class)... hashCode()-- computes the hash value of a key hashCode()-- computes the hash value of a key toString()-- converts the class to a string toString()-- converts the class to a string

Interfaces Inheritance is also employed here Inheritance is also employed here But interfaces inherit specification But interfaces inherit specification Classes inherit code (and data) Classes inherit code (and data) Thus classes derived from some abstract class will share an interface (proper inheritance) Thus classes derived from some abstract class will share an interface (proper inheritance) Inheritance of interfaces sometimes called subtyping Inheritance of interfaces sometimes called subtyping An object’s class indicates how the object is implemented An object’s class indicates how the object is implemented An object’s type refers to its interface An object’s type refers to its interface

Inheritance: Class vs Interface Class: An object’s implementation is given in terms of another’s implementation Class: An object’s implementation is given in terms of another’s implementation Interface (subtyping): One object can be used in place of another Interface (subtyping): One object can be used in place of another C++ and Java use both types of inheritance C++ and Java use both types of inheritance Smalltalk uses only class inheritance Smalltalk uses only class inheritance No subtyping, because variable types are not declared No subtyping, because variable types are not declared Instances of any class can be assigned to a variable as long as those instances support the operations performed on the variable’s operations Instances of any class can be assigned to a variable as long as those instances support the operations performed on the variable’s operations

Subclass, Subtype & Substitutability Subclass: Refers to the way of deriving, or inheriting, one class from another, i.e. in Java by the keyword extends Subclass: Refers to the way of deriving, or inheriting, one class from another, i.e. in Java by the keyword extends There are various heuristics to subclassing There are various heuristics to subclassing These are not recognizable from the program source, but rather from the kind of subclassing being implemented These are not recognizable from the program source, but rather from the kind of subclassing being implemented

Subclassing Taxonomy Specialization: the is_a relation. This is also the subtype relation, e.g. Physics is_a Science, Putin is_a Russian Specialization: the is_a relation. This is also the subtype relation, e.g. Physics is_a Science, Putin is_a Russian Composition: the has_a relation. E.g. a human has_a (n) arm. Composition: the has_a relation. E.g. a human has_a (n) arm. Specification: Parent has abstract methods that specify the behavior of the subclass Specification: Parent has abstract methods that specify the behavior of the subclass public MyGUI extends JFrame public MyGUI extends JFrame Most ideal type of inheritance Most ideal type of inheritance

Sublassing Taxonomy Construction:Just a trick, because there is no real relation between the class and its subclass (use the parent’s behavior) Construction:Just a trick, because there is no real relation between the class and its subclass (use the parent’s behavior) Use a Vector to implement a Stack: Use a Vector to implement a Stack: class Stack extends Vector{ public void push(Object item) addelement(item);} public boolean empty(){return isEmpty():}

Subclassing Taxonomy Generalization: generalize the behavior of the parent (the opposite of specialization). Generalization: generalize the behavior of the parent (the opposite of specialization). If you implement a background color Black&White and use this to define a BWWindow class, you generalize if you derive a ColorWindow from it. If you implement a background color Black&White and use this to define a BWWindow class, you generalize if you derive a ColorWindow from it. Better: subclass the other way round Better: subclass the other way round

Subclassing Taxonomy Extension: Add completely new behavior in the child. Add new functionality not in the parent Extension: Add completely new behavior in the child. Add new functionality not in the parent E.g. public class Properties extends Hashtable E.g. public class Properties extends Hashtable Use the parent Hashtable to store and retrieve, but also define a new method, e.g.: Use the parent Hashtable to store and retrieve, but also define a new method, e.g.: public synchronized void load(InputStream in) throws IOException;

Subclassing Taxonomy Limitation: If you do not have access to the parent, override the irrelevant methods, i.e. the subclass is a restriction of the parent class Limitation: If you do not have access to the parent, override the irrelevant methods, i.e. the subclass is a restriction of the parent class Of questionable value Of questionable value E.g. if you wanted to use Vector to implement a Set, override the elementAt(int index) method, since it is irrelevant E.g. if you wanted to use Vector to implement a Set, override the elementAt(int index) method, since it is irrelevant Can’t do this in this case anyway (method is final ) Can’t do this in this case anyway (method is final )

Subclass, Subtype and Substitutability Substitutability:When can one type be used in place of another? What does this mean? Substitutability:When can one type be used in place of another? What does this mean? E.g. in Pascal: E.g. in Pascal: Can Complex and Vector be used interchangeably in a program? Can Complex and Vector be used interchangeably in a program? In Pascal these are distinct type: type equivalent, but not type identical In Pascal these are distinct type: type equivalent, but not type identical type Cpmplex = record x:real; y:real end; type Vector = record x:real; y:real end;

Liskov Substitutability Principle Principle (Liskov): If for each object O 1 of type S there is an object O 2 of type T such that for all programs P defined in terms of T the behavior of P is unchanged where O 1 is substituted for O 2 then S is a subtype of T, or S can be substituted for T Principle (Liskov): If for each object O 1 of type S there is an object O 2 of type T such that for all programs P defined in terms of T the behavior of P is unchanged where O 1 is substituted for O 2 then S is a subtype of T, or S can be substituted for T This means: if you use O 1 instead of O 2 in P there is no observable change from running P with O2 This means: if you use O 1 instead of O 2 in P there is no observable change from running P with O2

Budd’s Version 1. Instances of the subclass must possess all data fields associated with the parent class 2. Instances of the subclass must implement, through inheritance at least, all functionality defined forthe parent class 3. Thus, an instance of a child class can mimic the behavior of the parent class and should be indistinguishable from an instance of the parent class if substituted in a similar situation

Remarks This is a test for determining substitutability This is a test for determining substitutability Note the removal of the overridden clause Note the removal of the overridden clause Note the no observable behavior!! Note the no observable behavior!!

Example Write some Java code to implement a typical bank account as given by the class CurrentAccount. Nothing special here. Write some Java code to implement a typical bank account as given by the class CurrentAccount. Nothing special here. Now define another account SpecialCurrentAccount by extending CurrentAccount that pays more interest, but requires that the account be opened for longer than the default period Now define another account SpecialCurrentAccount by extending CurrentAccount that pays more interest, but requires that the account be opened for longer than the default period

CurrentAccount public class CurrentAccount{ protected int balance; protected int period; public CurrentAccount(int balance, int period){ this.balance = balance; this.period = period;} public boolean openAccount(int balance){ this.balance = balance;} public boolean closeAccount{ if (balance > 0) return true; else return false;} public int getBalance(){return this.balance;}

public void setBalance(int balance){ this.balance = balance:} public int getPeriod(){return this.period;} public void setPeriod(int period){ this.period = period; }

SpecialCurrentAccount public class SpecialCurrentccount extends CurrentAccount{ private int defaultPeriod = 6; public SpecialCurrentAccount(int balance, int period}{ super(balance, period);} public boolean closeAccount(){ if (balance>0 && period>defaultPeriod) return true; else return false;} public int getDefaultPeriod(){ return this.defaultPeriod:} public void seDefaultPeriod(int defaultPeriod){ this.defaultPeriod = defaultPeriod;}

AccountTest public class AccountTest{ public void closeAnAccount(CurrentAccount ac){ System.out.println(“Account close result: ac.closeAccount()): }

Now Close 2 Accounts One is to be normal and the other special: One is to be normal and the other special: public static void main(String[] args){ AccountTest test =new AccountTest(); CurrentAccount ac = new CurrentAccount(100,2); SpecialCurrentAccount sac = new SpecialCurrentAccount (200,5); test.closeAnAccount(ac); test.closeAnAccount(sac); }

Result Liskov Substitution Principle is violated! Liskov Substitution Principle is violated! If the bank customer uses a SpecialCurrentAccount where a CurrentAccount is expected, the customer is in for a surprise If the bank customer uses a SpecialCurrentAccount where a CurrentAccount is expected, the customer is in for a surprise Big problem: the outcome is only predictable by examining the code Big problem: the outcome is only predictable by examining the code Way out: use an abstract base class: Way out: use an abstract base class:

Account +closeAccount:bool CurrentAccount SpecialCurrentAccount