Lecture 17: Polymorphism (Part I)

Slides:



Advertisements
Similar presentations
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
Advertisements

Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 9: Inheritance and Interfaces.
1 Inheritance Readings: Writing classes Write an Employee class with methods that return values for the following properties of employees at a.
Copyright 2008 by Pearson Education Building Java Programs Subtype Polymorphism; Sorting (an extended programming example)
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Critters; Subtype Polymorphism Reading: HW9 Handout, Chapter 9.2.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading:
Copyright 2010 by Pearson Education Topic 31 - inheritance.
Building Java Programs Chapter 9
Unit 7 Textbook Chapter 9.
Building Java Programs Chapter 9 Inheritance and Interfaces Copyright (c) Pearson All rights reserved.
AD Lecture #2 Object Oriented Programming Three Main Principles 1 Inheritance Encapsulation Polymorphism Abstract.
Inheritance - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University 1050 Wachman Hall, Main Campus
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.
CS 112 Introduction to Programming Inheritance Hierarchy; Polymorphism Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading:
CSE 143 Lecture 23 Polymorphism; the Object class read slides created by Marty Stepp and Ethan Apter
1 Building Java Programs Chapter 9: Inheritance and Interfaces These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 9: Inheritance and Interfaces.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
1 Building Java Programs Chapter 9: Inheritance and Interfaces These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be.
Building Java Programs Chapter 9 Inheritance and Interfaces Copyright (c) Pearson All rights reserved.
Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones EE 422CGenerics 1.
CSE 143 Lecture 12 Inheritance slides created by Ethan Apter
Copyright 2010 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading: 9.1.
Copyright 2009 by Pearson Education Building Java Programs Chapter 9: Inheritance and Interfaces Lecture 9-2: Polymorphism reading: 9.2 self-check: #5-9.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-3: Polymorphism reading: 9.3.
CSE 143 Lecture 13 Inheritance slides created by Ethan Apter
1 Interacting with the superclass (continued) suggested reading:9.4.
Building Java Programs Chapter 9 Inheritance and Interfaces Copyright (c) Pearson All rights reserved.
Building Java Programs Chapter 9 Interfaces Copyright (c) Pearson All rights reserved.
Building Java Programs
Lecture 16: Polymorphism (Part I)
Lecture 25: Inheritance and Polymorphism
Building Java Programs Chapter 9
Inheritance Based on slides by Ethan Apter
Building Java Programs Chapter 9
Inheritance - CIS 1068 Program Design and Abstraction
Building Java Programs
Building Java Programs Chapter 9
Lecture 15: More Inheritance
Lecture 17: Polymorphism (Part II)
© University of Washington, all rights reserved.
Building Java Programs
Topic 32 - Polymorphism.
CSE 143 Lecture 22 The Object class; Polymorphism read
Topic 32 - Polymorphism.
Building Java Programs
Building Java Programs
CSE 143 Lecture 22 The Object class; Polymorphism read
Building Java Programs
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Building Java Programs
Law firm employee analogy
Lecture 14: Inheritance Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
Inheritance Readings: 9.1.
Lecture 15: Inheritance II
Lecture 18: Polymorphism (Part II)
CSE 142 Lecture Notes Inheritance, Interfaces, and Polymorphism
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
CSE 143 Lecture 23 Polymorphism; the Object class read
Chapter 9 9-3: Polymorphism reading: 9.3
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 23 Inheritance and the Object class; Polymorphism
Building Java Programs
Programming Abstractions in C++, Chapter 19
Presentation transcript:

Lecture 17: Polymorphism (Part I) Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson 2013. All rights reserved.

Polymorphism

Polymorphism polymorphism: Ability for the same code to be used with different types of objects and behave differently with each.(Part I Lecture) System.out.println can print any type of object. Each one displays in its own way on the console. Ability for a method to take on many forms. (Part II Lecture)

Coding with polymorphism A variable of type T can hold an object of any subclass of T. Employee ed = new Lawyer(); You can call any methods from the Employee class on ed. When a method is called on ed, it behaves as a Lawyer. System.out.println(ed.getSalary()); // 50000.0 System.out.println(ed.getVacationForm()); // pink Student s1=new GradStudent(); s1.computeGrade(); //calls GradStudent’s version.

Polymorphism and parameters You can pass any subtype of a parameter's type. 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.getSalary()); System.out.println("v.days: " + empl.getVacationDays()); System.out.println("v.form: " + empl.getVacationForm()); System.out.println(); OUTPUT: salary: 50000.0 salary: 50000.0 v.days: 15 v.days: 10 v.form: pink v.form: yellow

Polymorphism and parameters You can pass any subtype of a parameter's type. 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.getSalary()); System.out.println("v.days: " + empl.getVacationDays()); System.out.println("v.form: " + empl.getVacationForm()); System.out.println(); Note: This code will remain the same regardless of how many subclasses of Employee we add later in our code.

Polymorphism and arrays Arrays of superclass types can store any subtype as elements. public class EmployeeMain2 { public static void main(String[] args) { Employee[] e = { new Lawyer(), new Secretary(), new Marketer(), new LegalSecretary() }; for (int i = 0; i < e.length; i++) { System.out.println("salary: " + e[i].getSalary()); System.out.println("v.days: " + e[i].getVacationDays()); System.out.println(); } Output: salary: 50000.0 v.days: 15 v.days: 10 salary: 60000.0 salary: 55000.0

Exercise 1 Suppose that the following four classes have been declared: public class Foo { public void method1() { System.out.println("foo 1"); } public void method2() { System.out.println("foo 2"); public String toString() { return "foo"; public class Bar extends Foo { System.out.println("bar 2");

Exercise 1 What would be the output of the following client code? public class Baz extends Foo { public void method1() { System.out.println("baz 1"); } public String toString() { return "baz"; public class Mumble extends Baz { public void method2() { System.out.println("mumble 2"); What would be the output of the following client code? Foo[] pity = {new Baz(), new Bar(), new Mumble(), new Foo()}; for (int i = 0; i < pity.length; i++) { System.out.println(pity[i]); pity[i].method1(); pity[i].method2(); System.out.println();

Exercise 1’s Answers Output: baz baz 1 foo 2 foo foo 1 bar 2 mumble 2 Foo[] pity = {new Baz(), new Bar(), new Mumble(), new Foo()}; for (int i = 0; i < pity.length; i++) { System.out.println(pity[i]); pity[i].method1(); pity[i].method2(); System.out.println(); } Output: baz baz 1 foo 2 foo foo 1 bar 2 mumble 2

Exercise 2 The order of the classes is jumbled up. The methods sometimes call other methods (tricky!). public class Lamb extends Ham { public void b() { System.out.print("Lamb b "); } public class Ham { public void a() { System.out.print("Ham a "); b(); System.out.print("Ham b "); public String toString() { return "Ham";

Exercise 2 What would be the output of the following client code? public class Spam extends Yam { public void b() { System.out.print("Spam b "); } public class Yam extends Lamb { public void a() { System.out.print("Yam a "); super.a(); public String toString() { return "Yam"; What would be the output of the following client code? Ham[] food = {new Lamb(), new Ham(), new Spam(), new Yam()}; for (int i = 0; i < food.length; i++) { System.out.println(food[i]); food[i].a(); System.out.println(); // to end the line of output food[i].b(); System.out.println();

Polymorphism at work Lamb inherits Ham's a. a calls b. But Lamb overrides b... public class Ham { public void a() { System.out.print("Ham a "); b(); } public void b() { System.out.print("Ham b "); public String toString() { return "Ham"; public class Lamb extends Ham { System.out.print("Lamb b "); Lamb's output from a: Ham a Lamb b

Exercise 2’s Answers Output: Ham Ham a Lamb b Lamb b Ham a Ham b Ham b Ham[] food = {new Lamb(), new Ham(), new Spam(), new Yam()}; for (int i = 0; i < food.length; i++) { System.out.println(food[i]); food[i].a(); food[i].b(); System.out.println(); } Output: Ham Ham a Lamb b Lamb b Ham a Ham b Ham b Yam Yam a Ham a Spam b Spam b Yam a Ham a Lamb b

Casting references To use Lawyer methods on ed, we can type-cast it. A variable can only call that type's methods, not a subtype's. Employee ed = new Lawyer(); int hours = ed.getHours(); // ok; it's in Employee ed.sue(); // compiler error The compiler's reasoning is, variable ed could store any kind of employee, and not all kinds know how to sue . To use Lawyer methods on ed, we can type-cast it. Lawyer theRealEd = (Lawyer) ed; theRealEd.sue(); // ok ((Lawyer) ed).sue();// shorter version,two sets of()

More about casting The code crashes if you cast an object too far down the tree. Employee eric = new Secretary(); ((Secretary) eric).takeDictation("hi"); // ok ((LegalSecretary) eric).fileLegalBriefs(); // Class cast //exception // (Secretary object doesn't know how to file briefs) You can cast only up and down the tree, not sideways. Lawyer linda = new Lawyer(); ((Secretary) linda).takeDictation("hi"); // error Casting doesn't actually change the object's behavior. It just gets the code to compile/run. ((Employee) linda).getVacationForm() // pink (Lawyer's)

Exercise 3 Assume that the following classes have been declared: public class Snow { public void method2() { System.out.println("Snow 2"); } public void method3() { System.out.println("Snow 3"); public class Rain extends Snow { public void method1() { System.out.println("Rain 1"); System.out.println("Rain 2");

Exercise 3 public class Sleet extends Snow { public void method2() { System.out.println("Sleet 2"); super.method2(); method3(); } public void method3() { System.out.println("Sleet 3"); public class Fog extends Sleet { public void method1() { System.out.println("Fog 1"); System.out.println("Fog 3");

Exercise 3 What happens when the following examples are executed? Snow var1 = new Sleet(); var1.method2(); Example 2: Snow var2 = new Rain(); var2.method1(); Example 3: Snow var3 = new Rain(); ((Sleet) var3).method3();

Exercise 3 Answers Example: Output: Snow var1 = new Sleet(); variable var1.method2(); Output: Sleet 2 Snow 2 Sleet 3 variable Snow method2 method3 object method1 method2 (method3) Rain method2 method3 Sleet method1 (method2) method3 Fog

Exercise 3 Answers Example: Output: Snow var2 = new Rain(); variable var2.method1(); Output: None! There is an error, because Snow does not have a method1. variable Snow method2 method3 object method1 method2 (method3) Rain method2 method3 Sleet method1 (method2) method3 Fog

Exercise 3 Answers Example: Output: Snow var3 = new Rain(); ((Sleet) var3).method2(); Output: None! There is an error because a Rain is not a Sleet. Snow method2 method3 object variable method1 method2 (method3) Rain method2 method3 Sleet method1 (method2) method3 Fog

Review Example Employee one=new Secretary(); //upcast, always ok one.getSalary(); //calls Secretary’s version one.takeDictation(); //error, even though one holds a //Secretary object, one is an Employee reference //and can only call Employee’s methods. //here’s how to fix the above error. ((Secretary) one).takeDictation();//cast then call //can’t cast too far down the tree ((LegalSecretary) one).fileLegalBriefs(); //error

Review Example 2 LegalSecretary two=new LegalSecretary(); //upcast doesn’t change behavior. ((Secretary) two).getSalary(); //still LegalSecretary’s //version ((Employee) two).getSalary(); //still LegalSecretary’s version //can’t cast sideways ((Lawyer) two).sue(); //error

Homework Redo the 3 exercises in this lecture and check your answers. Then complete the Polymorphism Worksheet.