CS 112 Introduction to Programming Inheritance Hierarchy; Polymorphism Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Slides:



Advertisements
Similar presentations
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Advertisements

Class Hierarchy (Inheritance)
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
CS 112 Introduction to Programming
CS 211 Inheritance AAA.
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
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Static Data; More Inheritance reading:
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 9: Inheritance and Interfaces.
Review of Object-Oriented Concepts in JAVA Object-Oriented Concepts supported by JAVA. Advantages of Object-Orientation. Inheritance. Abstract Classes.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Inheritance Readings: Writing classes Write an Employee class with methods that return values for the following properties of employees at a.
Review of Object-Oriented Concepts in JAVA Object-Oriented Concepts supported by JAVA. Object-Oriented Concepts supported by JAVA. Advantages of Object-Orientation.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading:
Copyright 2010 by Pearson Education Topic 31 - inheritance.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
AD Lecture #2 Object Oriented Programming Three Main Principles 1 Inheritance Encapsulation Polymorphism Abstract.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved Polymorphism Polymorphism is an object-oriented concept that allows.
CSC 142 Computer Science II Zhen Jiang West Chester University
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 19: encapsulation, inheritance reading: (Slides adapted from Stuart.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading:
1 Building Java Programs Chapter 9: Inheritance and Interfaces These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Static Data; More Inheritance reading:
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that 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.
Copyright 2010 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading: 9.1.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Interacting with the Superclass ( super ) reading:
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Interacting with the Superclass ( super ); Discussion of Homework 9:
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Interacting with the Superclass ( super ); Discussion of Homework 9:
Inheritance ndex.html ndex.htmland “Java.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9: Inheritance and Interfaces Lecture 9-1.
CS 112 Introduction to Programming Class Inheritance Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
CS 112 Introduction to Programming Method Overriding; Object Hierarchy; Event-Driven Programming Yang (Richard) Yang Computer Science Department Yale University.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-3: Polymorphism reading: 9.3.
CS 112 Introduction to Programming Critters, Polymorphism Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
1 Interacting with the superclass (continued) suggested reading:9.4.
Lecture 12 Inheritance.
Building Java Programs Chapter 9
Adapted from slides by Marty Stepp and Stuart Reges
Building Java Programs Chapter 9
03/10/14 Inheritance-2.
Lecture 15: More Inheritance
Lecture 9-2: Interacting with the Superclass (super);
Designing for Inheritance
Adapted from slides by Marty Stepp and Stuart Reges
Building Java Programs
Building Java Programs
Building Java Programs
Inheritance Readings: 9.1.
Lecture 15: Inheritance II
The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs. Large-scale projects face.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Presentation transcript:

CS 112 Introduction to Programming Inheritance Hierarchy; Polymorphism Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

2 Admin  Class project m Please work on forming teams

Recap: Inheritance  Inheritance: A way to allow a software developer to reuse classes by deriving a new class from an existing one, e.g., m Secretary extends Employee m InstaPic extends Picture  When constructing an object, Java makes sure that the constructor of the parent is first called m insertion of super() if no super(…) as first statement in a constructor m slight complexity: Java adds a default constructor for each class, if the class has no constructor  Overriding methods allow a child class to revise the behaviors of the parent class  Design principle: when overriding parent’s behavior, derive behavior (e.g., 1.2 times base pay), not the final outcome (e.g., $60,000) 3

4 Example Extension  The boss wants to give employees more vacation days the longer they've been with the firm: m For each year worked, award 2 additional vacation days. m When an Employee object is constructed, we'll pass in the number of years the person has been with the firm. m Exercise: Make necessary modifications to the Employee class.

Solution: Add Served Years to Employee public class Employee { private String name; private int years; public Employee(String name, int years) { this.name = name; this.years = years; } public Employee(String name) { this.name = name; years = 0; // 0 year service as default } public int vacationDays () { return * years; } … } 5

6 Outline  Admin and recap  Class inheritance o why and how? o inheritance and object construction o overriding and using overridden methods o inheritance and field access

7 Inheritance and Fields  Setting: To retain the best lawyers, the firm will pay a lawyer the base and $5000 for each year in the firm public class Lawyer extends Employee { … public double pay() { return super.pay() * years; } … }

8 Problem  Fields declared private cannot be accessed from subclasses m Reason: so that subclassing cannot break encapsulation m Q: how to get around this limitation?

9 Solution 1  Java provides a third visibility modifier to denote fields/methods to be accessible by only child classes: protected public class Employee { private String name; protect int years; public Employee(String name, int years) { this.name = name; this.years = years; } … }

10 Solution 2  Add an accessor for any field needed by the subclass public class Employee { private String name; private int years; public Employee(String name, int initialYears) { this.name = name; years = initialYears; } public int getYears() { return years; }... } public class Lawyer extends Employee { public Lawyer(String name, int years) { super(name, years); } public double pay() { return super.pay() * getYears(); }... }

11 Discussion  Which design do you like?  Design 1: make year protected  Design 2: Add public getYear()  Settings where protected is more appropriate than adding a public accessor?  Adding public getYear() makes it available to not only child class, but also all other classes

12 Outline  Admin and recap  Class inheritance o why and how? o inheritance and object construction o overriding and using overridden methods o inheritance and field access o inheritance hierarchy

Levels of inheritance Multiple levels of inheritance in a hierarchy are allowed. Example: A legal secretary is the same as a regular secretary but makes more money (10% more) and can file legal briefs. Exercise: Implement the LegalSecretary class. 13

LegalSecretary class // A class to represent legal secretaries. public class LegalSecretary extends Secretary { public void fileLegalBriefs() { System.out.println("I could file all day!"); } public double pay() { return super.pay() * 1.1 ; } 14

Partner class  Partner is a senior lawyer that can get bonus. Thus it supports: awardBonus(double bonus) 15

Partner class // A class to represent partner. public class Partner extends Lawyer { private double bonus; public void awardBonus(double bonus) { this.bonus = bonus; } public double pay() { return super.pay() + bonus ; } 16

17 Class Hierarchies  Many large-scale software systems define class hierarchies, where the root defines the common behaviors Employee SecretaryLawyerMarketer LegalSecretary Partner

18 Class Hierarchies: Another Example Animal ReptileBirdMammal SnakeLizardBatHorseParrot

19 The Object Class  A class called Object is defined in the java.lang package of the Java standard class library  All classes in Java are derived from the Object class  even if a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class  the Object class is therefore the ultimate root of all class hierarchies  The Object class contains a few most basic methods, which are inherited by all classes m toString() m equals() m clone()

20 The Object Class: the toString Method  The toString method in the Object class is defined to return a string that contains the name of the object’s class and a hash value  Every time we have defined toString, we have actually been overriding it  Shortcut: If the parameter to the println method is an object, the method will invoke the toString method

21 Outline  Admin and recap  Class inheritance o why and how? o inheritance and object construction o overriding and using overridden methods o inheritance and field access o inheritance hierarchy o inheritance and method binding

22 Example Setting  It turns out that the vacation bonus policy does not apply to secretaries: they get fixed 10 days vacation, not ( * years)

23 Solution 1  We set all Secretaries to 0 years of service because they do not have vacation bonus public class Secretary extends Employee { public Secretary(String name, int years) { super(name, 0); } public void prepareDoc(String text) { System.out.println(“ Working on doc “ + text); }

24 Problem  Solution 1 is not good:  If we call getYears() on a Secretary object, we get 0 m What if we wanted to give other rewards to all employees based on years of service?

Idea: Separation public class Employee { private String name; private int years; public int vacationDays () { return * years; } … } 25 Separate base days and bonus days to allow adaptation

Improved Employee code  Separate the standard 10 vacation days from those that are awarded based on seniority. public class Employee { private int years; public Employee(int initialYears) { years = initialYears; } public int getVacationDays() { return 10 + getSeniorityVacation(); } // vacation days given for each year in the company public int getSeniorityVacation() { return 2 * years; }... }  How does this help us improve the Secretary ?

Improved Secretary code  Secretary can override getSeniorityVacation. public class Secretary extends Employee { public Secretary(String name, int years) { super(name, years); } // Secretaries don't get a bonus for their years of service. public int getSeniorityVacation() { return 0; } public void prepareDoc(String text) { System.out.println(”Working on text: " + text); }

Example Client public class Firm { public static void main(String args) { Secretary seth = new Secretary(“Seth”, 10); int vacDays = seth.getVacationDays(); } // Defined in class Employee public int getVacationDays() { return 10 + getSeniorityVacation(); } // Defined in class Employee public int getSeniorityVacation() { return 2 * years; } // Defined in class Secretary public int getSeniorityVacation() { return 0; } Secretary obj’s method

Example Client public class Firm { public static void main(String args) { Lawyer larry = new Lawyer(“Larry”, 10); int vacDays = larry.getVacationDays(); } // Defined in class Employee public int getVacationDays() { return 10 + getSeniorityVacation(); } // Defined in class Employee public int getSeniorityVacation() { return 2 * years; }

Summary  The method invoked is always determined by the object, not the class.  Hence when a method in a base class invokes the name of another method defined in the base class, the real method invoked can be defined either in the base class, or a child class.  This is called dynamic binding. // Defined in class Employee public int getVacationDays() { return 10 + getSeniorityVacation(); }

31 Outline  Admin and recap  Class inheritance o why and how? o inheritance and object construction o overriding and using overridden methods o inheritance and field access o inheritance hierarchy o inheritance and polymorphism

What is Polymorphism?  polymorphism: Ability for the same code to be used with different types of objects and behave differently with each.

33 Recap: Reference Variables  Interaction with an object occurs through object reference variables  An object reference variable holds the reference (address, the location) of an object ChessPiece bishop1 = new ChessPiece(); bishop1

34 Recap: Object Reference Variable  Object reference variable assignment copies address, creating aliases bishop2 = bishop1; Before bishop1bishop2 After bishop1bishop2

Polymorphic Reference through Inheritance  A variable of type T can hold an object of class T or descendent of T, e.g., Employee emp = new Employee(“Ed”); emp = new Lawyer(“Larry”); emp = new LegalSecretary(“Lisa”);  When we use a variable v of type T to refer to objects both of base type T and descent of T, we say that it is a polymorphic reference through inheritance

Polymorphic Reference and Method  You can call any methods defined in the based class T (e.g., Employee ) class on polymorphic reference of type T (e.g., emp )  When you invoke a method through a polymorphic reference variable, it is the type of the object being referenced, not the reference type, that determines which method is invoked.  Careful use of polymorphic references can lead to elegant, robust software designs

Polymorphic Reference through Inheritance 37 Employee ed Reference variable type Object type: Lawyer Object type: Secretary ed.vacationDays() // 15 ed.vacationDays() // 10

Polymorphic Reference: Example Employee emp; emp = new Lawyer("Larry"); System.out.println ( emp.vacationDays() ); // OUTPUT: 15 System.out.println ( emp.vacationForm() ); // OUTPUT: pink emp = new LegalSecretary(“Lisa"); System.out.println ( emp.vacationDays() ); // OUTPUT: 10 System.out.println ( emp.vacationForm() ); // OUTPUT: yellow 38

Polymorphic Method Parameter  Define a method that takes a reference to a base type and apply to all derived types.  This is how print in PrintStream is defined: void print(Object obj) { // all objects have the toString() method // convert to string and then output }

Polymorphic Method Parameter: Example public class EmployeeMain { public static void main(String[] args) { Lawyer lisa = new Lawyer(); Secretary steve = new Secretary(); printInfo(lisa); printInfo(steve); } public static void printInfo(Employee empl) { System.out.println("salary: " + empl.pay()); System.out.println("v.days: " + empl.vacationDays()); System.out.println("v.form: " + empl.vacationForm()); System.out.println(); } OUTPUT:salary: v.days: 15v.days: 10 v.form: pinkv.form: yellow

Polymorphism and Arrays  A common usage of polymorphism is to define an array of a base type, but different entries refer to different types of objects m To handle a heterogeneous population of objects with uniformity

Polymorphism and Arrays: Example public class Staff { private Employee[] staffList; public Staff() { staffList = new Employee[4]; staffList[0] = new Lawyer("Lisa"); staffList[1] = new Secretary("Sally"); staffList[2] = new Marketer("Mike"); staffList[3] = new LegalSecretary("Lynne"); } public void payday() { for (int count = 0; count < staffList.length; count++) { System.out.printf("%-10s:", staffList[count].name()); System.out.printf("$%.2f\n", staffList[count].pay()); System.out.println(" "); } Works on any mix of Employee objects

Exercise: Extending the Program: Hourly  Include a new type of secretary who are paid by hours. 43