Intermediate Java 95-713 Sakir YUCEL MISM/MSIT Carnegie Mellon University Lecture: Polymorphism Slides adapted from Prof. Steven Roehrig.

Slides:



Advertisements
Similar presentations
Identity and Equality Based on material by Michael Ernst, University of Washington.
Advertisements

A subclass can add new private instance variables A subclass can add new public, private or static methods A subclass can override inherited methods A.
Inheritance Lakshmish Ramaswamy. Example A Rectangle class with area method A Circle class with area method Array containing references to circles & rectangles.
Effective Java, Chapter 3: Methods Common to All Objects.
1 Class Design CS 3331 Fall Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode method.
Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
Object-Oriented Programming MISM/MSIT Carnegie Mellon University Lecture 4: Polymorphism.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Object-Oriented Programming MISM/MSIT Carnegie Mellon University Professor Roehrig’s Notes.
Intermediate Java II Sakir YUCEL MISM/MSIT Carnegie Mellon University Lecture: Exception Handling Slides adapted from Prof. Steven Roehrig.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Java Object Model Part 2: the Object class. 2 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass.
Object-Oriented Programming C Sakir YUCEL MISM/MSIT Carnegie Mellon University Lecture 5: Polymorphism Slides adapted from Prof. Steven Roehrig.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Searching. Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
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.
Searching Also: Logarithms. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an.
Advanced Inheritance Concepts. In this chapter, we will cover: Creating and using abstract classes Using dynamic method binding Creating arrays of subclass.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Viswanathan Inheritance and Polymorphism Course Lecture Slides 2 nd June 2010 “ We are.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
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.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
Non-static classes Part 2 1. Methods  like constructors, all non-static methods have an implicit parameter named this  for methods, this refers to the.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun.
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.,
DATA STRUCTURES Lecture: Polymorphism Slides adapted from Prof. Steven Roehrig.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance (Part 2) KomondorBloodHound PureBreedMix Dog Object.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Java Type System and Object Model Horstmann ch , 7.7.
Lecture 4: Extending Classes. Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you.
CMSC 202 Inheritance II. Version 10/092 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Class Design CS 3331 Sec 6.1 & 6.3 of [Jia03]. 2 Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode.
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.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Classes Revisited Chapter 8.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Object-oriented Programming in Java
Lecture 17: Polymorphism (Part II)
Extending Classes.
Inheritance 2nd Lecture
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Object-Oriented Programming
Lecture 15: Inheritance II
Lecture 18: Polymorphism (Part II)
CS/ENGRD 2110 Spring 2019 Lecture 6: Consequence of type, casting; function equals
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
Presentation transcript:

Intermediate Java Sakir YUCEL MISM/MSIT Carnegie Mellon University Lecture: Polymorphism Slides adapted from Prof. Steven Roehrig

Today’s Topics  Upcasting again  Method-call binding  Why polymorphism is good  Constructors and polymorphism  Downcasting  Several digressions: the Object class, object wrappers, the Class class, reflection

Upcasting Again class CellPhone { cellPhone() { //…} public void ring(Tune t) { t.play(); } } class Tune { public void play() { System.out.println("Tune.play()"); } class ObnoxiousTune extends Tune{ ObnoxiousTune() { // …} // … }

An ObnoxiousTune “is-a” Tune public class DisruptLecture { public static void main(String[] args) { CellPhone noiseMaker = new CellPhone(); ObnoxiousTune ot = new ObnoxiousTune(); noiseMaker.ring(ot); // ot works though Tune called for } Tune ObnoxiousTune A “UML” diagram

Aspects of Upcasting  Upcasting is a cast  The exact type of the object is lost  What gets printed in the CellPhone example?  Tune.play() (what were you expecting?)  Is this “the right thing to do”?  The alternative: write separate ring() methods for each subclass of Tune?

Another Example class CellPhone { CellPhone() { //…} public void ring(Tune t) { t.play(); } } class Tune { Tune() { //…} public void play() { System.out.println("Tune.play()"); } class ObnoxiousTune extends Tune{ ObnoxiousTune() { // …} public void play() { System.out.println("ObnoxiousTune.play()"); }

Polymorphism  The second example prints ObnoxiousTune.play()  Since an ObnoxiousTune object was sent to ring(), the ObnoxiousTune’s play() method is called.  This is called “polymorphism”  Most people think it’s “the right thing to do”

Method-Call Binding  The correct method is attached (“bound”) to the call at runtime.  The runtime system discovers the type of object sent to ring(), and then selects the appropriate play() method: if it’s a Tune object, Tune’s play() is called if it’s an ObnoxiousTune object, ObnoxiousTune’s play() is called

Is Java Always Late-Binding?  Yes, always, except for final, static and private methods.  final methods can’t be overridden, so the compiler knows to bind it.  The compiler may be able to do some speed optimizations for a final method, but we programmers are usually lousy at estimating where speed bottlenecks are…  In C++, binding is always at compile-time, unless the programmer says otherwise.

Another Polymorphism Example public static void main(String[] args) { CellPhone noiseMaker = new CellPhone(); Tune t; double d = Math.random(); if (d > 0.5) t = new Tune(); else t = new ObnoxiousTune(); noiseMaker.ring(t); }

References and Subclasses  We’ve seen that an ObnoxiousTune object can be supplied where a Tune object is expected.  Similarly, a Tune reference can refer to an ObnoxiousTune object.  In both cases, the basic question is: “Is an ObnoxiousTune really a proper Tune?” Yes!  This doesn’t work the other way around: any old Tune may not be an ObnoxiousTune.  So, an ObnoxiousTune reference cannot refer to a Tune object.

Let’s Fool the Compiler! public static void main(String[] args) { CellPhone noiseMaker = new CellPhone(); Tune t1 = new Tune(); Tune t2 = new ObnoxiousTune(); noiseMaker.ring(t1); noiseMaker.ring((Tune)t2); } ObnoxiousTune.play() Nothing changes… ObnoxiousTune.play() is still printed.

Let’s Fool the Compiler! public static void main(String[] args) { CellPhone noiseMaker = new CellPhone(); Tune t1 = new Tune(); Tune t2 = new ObnoxiousTune(); noiseMaker.ring(t1); noiseMaker.ring((ObnoxiousTune) t2); } Nothing changes…

Let’s Fool the Compiler! public static void main(String[] args) { CellPhone noiseMaker = new CellPhone(); Tune t1 = new Tune(); Tune t2 = new ObnoxiousTune(); noiseMaker.ring((ObnoxiousTune) t1); noiseMaker.ring(t2); } This compiles, but gets a CastClassException at runtime (even though Tune has a play() method). “Downcasting” can be dangerous!

Extensibility I public static void main(String[] args) { CellPhone noiseMaker = new CellPhone(); SimpleInput keyboard = new SimpleInput(); System.out.println("Enter number of tunes:"); int numTunes = keyboard.nextInt(); Tune[] tunes = new Tune[numTunes]; for (int i = 0; i < numTunes; i++) { System.out.println("Enter tune type"); System.out.println("(Tune=1, ObnoxiousTune=2)"); int tuneType = keyboard.nextInt(); switch(tuneType) { case 1: tunes[i] = new Tune(); break; case 2: tunes[i] = new ObnoxiousTune(); break; default: tunes[i] = new Tune(); break; } for (int i = 0; i < tunes.length; i++) noiseMaker.ring(tunes[i]); }

Extensibility II public class NiceTune extends Tune { NiceTune() {} public void play() { System.out.println("NiceTune.play()"); }

Extensibilty III public static void main(String[] args) { CellPhone noiseMaker = new CellPhone(); SimpleInput keyboard = new SimpleInput(); System.out.println("Enter number of tunes:"); int numTunes = keyboard.nextInt(); Tune[] tunes = new Tune[numTunes]; for (int i = 0; i < numTunes; i++) { System.out.println("Enter tune type"); System.out.println("(Tune=1, ObnoxiousTune=2, NiceTune = 3)"); int tuneType = keyboard.nextInt(); switch(tuneType) { case 1: tunes[i] = new Tune(); break; case 2: tunes[i] = new ObnoxiousTune(); break; case 3: tunes[i] = new NiceTune(); break; default: tunes[i] = new Tune(); break; } for (int i = 0; i < tunes.length; i++) noiseMaker.ring(tunes[i]); }

Extensibility  The Tunes program allows additional subclasses to be constructed and easily integrated.  Polymorphism is the key in letting this happen.  It was OK to make Tune objects.  How to prevent creating base class objects?

Abstract Classes  As always, get the compiler involved in enforcing our decisions.  Now it’s a compiler error if we try to make a Glyph object (but Glyph references are OK).  Subclasses are abstract (and we must so state) until all abstract methods have been defined. abstract class Glyph { abstract void draw(); Glyph() { System.out.println(“Glyph() before draw”); draw(); System.out.println(“Glyph() after draw”); }

Glyph Example (cont.) class RoundGlyph extends Glyph { int radius = 1; RoundGlyph(int r) { radius = r; System.out.println(“RoundGlyph(), radius=“ + radius); } void draw() { System.out.println(“RoundGlyph.draw(), radius=“ + radius); } public class GlyphTest { public static void main(String[] args) { new RoundGlyph(5); }

Glyph Example (cont.)  This produces  Guideline for constructors: “Do as little as possible to set the object into a good state, and if you can possibly avoid it, don’t call any methods.” Glyph() before draw() RoundGlyph.draw(), radius=0 Glyph() after draw() RoundGlyph(), radius= 5

But What If Draw() Isn’t Abstract? abstract class Glyph { void draw() { System.out.println(“Glyph.draw()”); } abstract void doNothing(); // added to keep Glyph abstract Glyph() { System.out.println(“Glyph() before draw”); draw(); System.out.println(“Glyph() after draw”); }

Glyph Example (cont.)  The Glyph constructor is at work creating the Glyph “sub-object” within a RoundGlyph object.  draw() is overridden in RoundGlyph.  A RoundGlyph object is being created.  RoundGlyph’s draw() method is called  Polymorphism rules!

Inheritance is Cool, But… Composition + Inheritance is Cooler abstract class Actor { abstract void act(); } class HappyActor extends Actor { public void act() { //…} } class SadActor extends Actor { public void act() { //…} } class Stage { Actor a = new HappyActor(); void change() { a = new SadActor(); } void go() { a.act(); } } public class Transmogrify { public static void main(String[] args){ Stage s = new Stage(); s.go(); //happy actor s.change(); s.go() // sad actor }

H&C’s Tips for Inheritance  Place common operations and fields in the superclass.  Don’t use protected fields very often.  Use inheritance to model the “is-a” relationship.  Don’t use inheritance unless all inherited methods make sense.  Use polymorphism, not type information.  Don’t overuse reflection.

Digression: The Object Class  Object is the ancestor of every class.  We don’t need to say, e.g.,  We can use an Object reference to refer to any object.  But to use any of the methods of Employee, we must cast to the correct type. class Employee extends Object Object obj = new Employee(“Harry Hacker”, 35000); int salary = ((Employee) obj).getSalary();

Some Object Methods  clone(): Creates and returns a copy of this object. Returns an Object.  equals(): Indicates whether some other object is "equal to" this one. Returns a Boolean.  getClass(): Returns the runtime class of an object. Returns a Class.  toString(): Returns a string representation of the object. Returns a String.

The equals() Method  As implemented in the Object class, this just tests whether two references point to the same memory.  This isn’t usually what we want.  Override to get correct behavior.  Pay attention to the Java language spec. to do it right.

The Rules For equals()  Reflexive: x.equals(x) is true  Symmetric: if x.equals(y) then y.equals(x)  Transitive: if x.equals(y) and y.equals(z) then x.equals(z)  Consistent: if x.equals(y) now, and x and y don’t change, then x.equals(y) later  If x is non-null, x.equals(null) is false

equals() Example class Employee { private String name; private double salary; private Date hireDay; public boolean equals(Object otherObject) { if (this == otherObject) return true; if (otherObject == null) return false; if (getClass() != otherObject.getClass()) return false; Employee other = (Employee)otherObject; return name.equals(other.name) && salary == other.salary && hireDay.equals(other.hireDay); }

Digression: Interpreting Strings as Numbers  To get an integer from the String s, use  parseInt() is a static method in Integer.  Another way:  Number is an abstract class, and n is either a Double or a Long int x = Integer.parseInt(s); NumberFormat formatter = NumberFormat.getNumberInstance(); Number n = formatter.parse(s); if (n instanceOf Double) Double d = (Double)n;

Digression: The Class Class  We saw that polymorphism is accomplished by the Java runtime system, which keeps track of every object’s type.  We can get the same information in code:  Recall e can refer to an Employee or a Manager. Employee e; … Class cl = e.getClass(); System.out.println(cl.getName() + " " + e.getName());

Other Ways to Get a Class  With the forName() method:  or, more directly: = ""; String className = "Manager"; // a // the following line may throw a checked exception Class cl = Class.forName(className); Class c11 = Manager.class; Class c12 = int.class; Class c13 = Double.class;

Digression in a Digression  A “checked exception” needs to be handled. try { String className = …; // get class name // the following line may throw a checked exception Class cl = Class.forName(className); … // do something with cl } catch(Exception e) { e.printStackTrace(); }

Methods of the Class Class  The concept of “reflection” is supported by Class methods that let you discover superclass info, constructors, methods and fields. import java.lang.reflect.*; // defines Constructor, Field, Method … String className = "Manager"; Class cl = Class.forName(className); Field[] fields = cl.getDeclaredFields(); for (int i = 0; i < fields.length; i++) System.out.println(fields[i].getName());

“Growing” an Array static Object arrayGrow(Object a) { Class cl = a.getClass(); if (!cl.isArray()) return null; Class componentType = cl.getComponentType(); int length = Array.getLength(a); int newLength = length * 11 / ; Object newArray = Array.newInstance (componentType, newLength); System.arraycopy(a, 0, newArray, 0, length); return newArray; }