Interfaces and Polymorphism 9.1 Using Interfaces for Code Reuse 9.1.1 Defining an Interface 9.1.2 implementing an interface 9.2 Converting between Class.

Slides:



Advertisements
Similar presentations
AP Computer Science TOPICS TO DISCUSS.equals() == instanceof operator compareTo Interfaces Abstract Classes.
Advertisements

METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert.
Interfaces and polymorphism Chapter 9. Interfaces  Used to express operations common to more than one purpose.  Example: You want to find the maximum.
Interfaces and Polymorphism Lesson - 8. Objectives Interfaces Supertype and subtype references Polymorphism Inner classes.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Nine: Interfaces and Polymorphism.
Computer Science A 9: 3/11. Inheritance Today: Inheritance (JC – CCJ ) I have to leave at 11am (but you can stay)
What is an Interface?? An interface is a ‘container’ which contains ONLY abstract methods. public interface Capitalizable { public abstract String outCaps()
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Interfaces and Polymorphism.
Chapter 8 – Interfaces and Polymorphism Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Interfaces. Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can.
Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.
Interfaces. Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Nine: Interfaces and Polymorphism.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
Chapter 9  Interfaces and Polymorphism 1 Chapter 9 Interfaces and Polymorphism.
Inheritance and Subclasses in Java CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University.
Object Oriented Programming, Interfaces, Callbacks Delegates and Events Dr. Mike Spann
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
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.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
What is an Interface?? An interface is a ‘class’ which contains ONLY abstract methods. public interface Capitalizable { public abstract String outCaps()
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
INTERFACES More OO Concepts. Interface Topics Using an interface Interface details –syntax –restrictions Create your own interface Remember polymorphism.
Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 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.,
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.
Fall 2006Adapted from Java Concepts Companion Slides1 Interfaces and Polymorphism Advanced Programming ICOM 4015 Lecture 10 Reading: Java Concepts Chapter.
CHAPTER 9 INTERFACES AND POLYMORPHISM Chapter Goals: –To learn about interfaces –To be able to convert between supertype and subtype references –To understand.
CHAPTER 9 INTERFACES AND POLYMORPHISM. CHAPTER GOALS To learn about interfaces To be able to convert between supertype and subtype references To understand.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao.
ICOM 4015 Fall 2008 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. ICOM 4015: Advanced Programming Lecture 9 Chapter.
Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Interfaces and Polymorphism CS 162 (Summer 2009).
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
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.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
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.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
EE2E1. JAVA Programming Lecture 4 Interfaces. Contents Interfaces – introduction Interfaces – introduction Example – generic sorting Example – generic.
Modern Programming Tools And Techniques-I
Chapter Goals To be able to declare and use interface types
Inheritance and Polymorphism
Lecture Notes – Interface and Polymorphism (Ch 9-10)
Interfaces and Polymorphism
Chapter 11 – Interfaces and Polymorphism
Chapter Three - Implementing Classes
Chapter 9 Inheritance and Polymorphism
Chapter 11 Interfaces and Polymorphism
Chapter 8 Class Inheritance and Interfaces
Object Oriented Programming
Presentation transcript:

Interfaces and Polymorphism 9.1 Using Interfaces for Code Reuse Defining an Interface implementing an interface 9.2 Converting between Class and Interface Types 9.3 Polymorphism 9.4 Callbacks 1

Assignment Read Sections and do self check exercises 1-7. Read Section 9.4 and do self-check exercises Review Exercises: R9.1 – R9.4, R9.6, R9.8 Due – See Syllabus Programming Exercises: P9.1, 9.2 & 9.4 (one prog) and 9.5 & 9.6 (one prog) Due – See Syllabus 2

Interface A Java interface declares a set of methods and their signatures. Unlike a class, it provides no implementation. To realize ( implement ) an interface, a class must supply all the methods that the interface requires. 3

A Java interface declares methods that classes are expected to implement. It encapsulates a set of associated behaviors that can be used by classes that are not similar. Contain no instance fields (cannot construct an object of an interface type) Interfaces can be implemented by many classes A class can implement multiple interfaces. 4

UML Diagram (Unified Modeling Language) 5 SkiJumper BirdAirplane > Flier fly() A Flier is one that flies. Three dissimilar classes

Interface Example public interface Flier { void fly(); } 6 Notice – no public modifier in the method header - Methods defined in an interface are all public by default.

Classes realizing Flier public class Bird implements Flier { public void fly() { System.out.println("Using my wings to fly"); } ================================================================== public class Airplane implements Flier { public void fly() { System.out.println("Using my jet engines to fly"); } ================================================================== public class SkiJumper implements Flier, Athlete, Comparable { public void fly() { System.out.println("Using skis to take me into the air"); } 7

Creating an ArrayList of Fliers ArrayList airborne = new ArrayList (); airborne.add(new SkiJumper(“Jumper”, “One”)); airborne.add(new SkiJumper(“Jumper”, “Two”)); airborne.add(new Airplane()); 8

UML Diagram 9 SkiJumper BirdAirplane > Flier fly() > Athlete train()

Another Interface public interface Athlete { void train(double hours); } 10 Used by SkiJumper class

Realizing the Interfaces public class SkiJumper implements Flier, Athlete { //Constructor{ } public void fly() { System.out.println("Using skis to take " + myFirstname + " " + myLastName + " into the air."); myNumberOfJumps++; } public void train(double hours) { System.out.println("I am on the slopes " + hours + " hours today."); myHoursTraining +=hours; } // more methods and private instance fields go here 11

public interface Comparable Method Summary intcompareTo(Object o)compareToObject - Used with the String class - Compares this object with the specified object for order (o). 12 Returns: Neg value if String less than o 0 if String equals o Pos value if String greater than o

Example String implements Comparable We can compare two strings by invoking the String method compareTo. String makes a promise to "define" what is means to compare two String objects. String s1 = ; String s2 = ; if (s2.compareTo(s1))……. 13

Examples public class Circle implements Comparable { public int compareTo(Object o) // Circle must define what it means to compare two Circle objects. } If we want to compare two circles, we must supply the method compareTo. 14

Examples public class Circle implements Comparable { public int compareTo(Object o) { Circle c = (Circle) o; if (this.equals(c)) return 0; if (this.radius < c.radius) return -1; return 1; } … // we have already defined equals for Circle. What if equals is not defined for Circle ? } 15

Examples public class Student implements Comparable { public int compareTo(Object o) { } … } 16

Examples public class Student implements Comparable { public int compareTo(Object o) { Student s = (Student) o; if (this.equals(s)) return 0; if (this.gpa < s.gpa) return -1; return 1; } … } 17

An interface….. "To be useful, an interface must be realized (implemented) by at least one Java class." – Rick Mercer A class may implement MANY interfaces. 18

Interfaces SHOULD NOT GROW! Classes have "contracts" with an interface. If the interface changes, all classes that realize the interface are affected! Interfaces allow for encapsulating similar behaviors between unrelated classes. 19

Interface All methods in an interface type are abstract, that is: Contains constants, method signatures or both. NO implementations. No instance variables. 20

Using interfaces Define a set of methods as an interface. Classes that realize the interface must support all the methods of the interface. Create classes that implement those methods. Compiler verifies that method calls are valid. (if not, the compiler will complain) 21

Interface declarations: All methods in an interface are public. The methods in the interface are not declared as public because they are public by default. When implementing the methods of the interface in a class, include the keyword public. 22

Interfaces Cannot be instantiated. Flier f = new Flier(); You can use interface name as a variable type; variable can refer to an object of any class that implements the interface. Flier b = new Bird(); Flier s = new SkiJumper(); 23 NO OK

Using interfaces Interfaces define types (sets of methods). A variable of type Flier must refer to an object that implements methods defined by Flier, not necessarily to an instance of Flier. Actual method invoked is defined by the object’s class, at run-time. (dynamic or late binding) 24

polymorphism… Late Binding: Behavior can vary depending on the actual type of an object. Occurs at runtime. The method selection takes place when the program runs. Early Binding (overloading):occurs at compile time. The compiler selects a method from several possible candidates. 25

polymorphism "In the object-oriented world, polymorphism refers to the ability of different kinds of objects to respond differently to the same commands, provided that the objects belong to classes with a common ancestor." K.N.King 26 The principle that the actual type of the object determines the method to be called is called polymorphism. The term “polymorphism” comes from the Greek words for “many shapes.”

Again… Early binding (overloading) of methods occurs if the compiler selects a method from several possible candidates as with overloaded methods. Late binding occurs if the method selection takes place when the program runs. 27

The importance of IS-A You can convert from a class type to an interface type if the class realizes (implements) the interface. String str = "word"; Comparable p = str;// You need a cast to convert from an interface type to a class type. String str = "word"; Comparable p = str; String t = p; // 28 NO OK

The importance of IS-A You can convert from a class type to an interface type if the class realizes the interface. String str = "word"; Comparable p = str;// You need a cast to convert from an interface type to a class type. String str = "word"; Comparable p = str; String t = (String)p; // 29 OK

instanceof operator The instanceof operator tests whether an object belongs to a particular type. What happens here? Flier aFlier = new SkiJumper("Joe","Smith"); Flier aFlier2 = new Airplane(); if (aFlier instanceof SkiJumper) System.out.println("That's right."); else System.out.println("NOT"); 30 EXAMPLE 1

instanceof operator The instanceof operator tests whether an object belongs to a particular type. What happens here? Flier aFlier = new SkiJumper("Joe","Smith"); Flier aFlier2 = new Airplane(); if (aFlier instanceof SkiJumper) System.out.println("That's right."); else System.out.println("NOT"); That's right. 31 EXAMPLE 1

instanceof operator The instanceof operator tests whether an object belongs to a particular type. What happens here? Flier aFlier = new SkiJumper("Joe","Smith"); Flier aFlier2 = new Airplane(); if (aFlier instanceof Flier) System.out.println("That's right."); else System.out.println("NOT"); 32 EXAMPLE 2

instanceof operator The instanceof operator tests whether an object belongs to a particular type. What happens here? Flier aFlier = new SkiJumper("Joe","Smith"); Flier aFlier2 = new Airplane(); if (aFlier instanceof Flier) System.out.println("That's right."); else System.out.println("NOT"); That's right. 33 EXAMPLE 2

instanceof operator The instanceof operator tests whether an object belongs to a particular type. What happens here? Flier aFlier = new SkiJumper("Joe","Smith"); Flier aFlier2 = new Airplane(); if (aFlier2 instanceof Flier) System.out.println("That's right."); else System.out.println("NOT"); 34 EXAMPLE 3

instanceof operator The instanceof operator tests whether an object belongs to a particular type. What happens here? Flier aFlier = new SkiJumper("Joe","Smith"); Flier aFlier2 = new Airplane(); if (aFlier2 instanceof Flier) System.out.println("That's right."); else System.out.println("NOT"); That's right. 35 EXAMPLE 3

instanceof operator The instanceof operator tests whether an object belongs to a particular type. What happens? Flier aFlier = new SkiJumper("Joe","Smith"); Flier aFlier2 = new Airplane(); if (aFlier2 instanceof SkiJumper) System.out.println("That's right."); else System.out.println("NOT"); 36 EXAMPLE 4

instanceof operator The instanceof operator tests whether an object belongs to a particular type. What happens? Flier aFlier = new SkiJumper("Joe","Smith"); Flier aFlier2 = new Airplane(); if (aFlier2 instanceof SkiJumper) System.out.println("That's right."); else System.out.println("NOT"); NOT 37 EXAMPLE 4

Polymorphism is NOT Overloading. Method signature refers to method name and parameters Overloading means methods have different signatures(different parameters). Overloading usually occurs in same class. BankAccount has two constructors. One of the constructors has one double parameter. One of the constructors has no parameters. The compiler chooses the appropriate method. 38

Polymorphism The actual type of the object determines which method is to be called. This is late binding (dynamic binding). The virtual machine, not the compiler, selects the appropriate method at run time. 39

Suppose C is a class that realizes the interfaces I and J. Which of the following assignments require a cast? C c = …; I i = …; J j = …; 1. c = i; 2. j = c; 3. i = j; 40

Suppose C is a class that realizes the interfaces I and J. Which of the following assignments require a cast? C c = …; I I = …; J j = …; 1. c = i; 2. j = c; 3. i = j; 41

Suppose C is a class that realizes the interfaces I and J. Which of the following assignments will throw an exception? C c = new C(); 1. I i = c; 2. J j = (J)i; 3. C d = (C)i; 42

Suppose C is a class that realizes the interfaces I and J. Which of the following assignments will throw an exception? C c = new C(); 1. I i = c; 2. J j = (J)i; 3. C d = (C)i; NONE 43

Consider the following DataSet class. p. 249 //Computes the average of a set of // data values. public class DataSet { public DataSet() { sum = 0; count = 0; maximum = 0; } //Adds a data value to the data // set public void add(double x) { sum = sum + x; if (count == 0 || maximum < x) maximum = x; count++; } //Returns the average of the added data. public double getAverage() { if (count == 0) return 0; else return sum / count; } //Returns the largest of the added data // or 0 if no data has been added public double getMaximum() { return maximum; } private double sum; private double maximum; private int count; } 44

Concerns Suppose we wanted to find the BankAccount with the highest balance? Suppose we wanted to find the Coin with the highest value? Suppose we wanted to find the Student with the highest gpa? 45

Solution: //Computes the average of a set of // data values. public class DataSet { public DataSet() { sum = 0; count = 0; maximum = 0; } //Adds a data value to the data // set public void add(BankAccount x) { sum = sum + x.getBalance(); if (count == 0 || maximum.getBalance() < x.getBalance()) maximum = x; count++; } //Returns the average of the added data. public double getAverage() { if (count == 0) return 0; else return sum / count; } //Returns the largest of the added data // or 0 if no data has been added public BankAccount getMaximum() { return maximum; } private double sum; private BankAccount maximum; private int count; } 46 BankAccount solution

Solution: //Computes the average of a set of // data values. public class DataSet { public DataSet() { sum = 0; count = 0; maximum = 0; } //Adds a data value to the data // set public void add(Coin x) { sum = sum + x.getValue(); if (count == 0 || maximum.getValue () < x.getValue ()) maximum = x; count++; } //Returns the average of the added data. public double getAverage() { if (count == 0) return 0; else return sum / count; } //Returns the largest of the added data // or 0 if no data has been added public Coin getMaximum() { return maximum; } private double sum; private Coin maximum; private int count; } 47 Coin solution

Solution: //Computes the average of a set of // data values. public class DataSet { public DataSet() { sum = 0; count = 0; maximum = 0; } //Adds a data value to the data // set public void add(Student x) { sum = sum + x.getGpa(); if (count == 0 || maximum.getGpa () < x.getGpa ()) maximum = x; count++; } //Returns the average of the added data. public double getAverage() { if (count == 0) return 0; else return sum / count; } //Returns the largest of the added data // or 0 if no data has been added public Student getMaximum() { return maximum; } private double sum; private Student maximum; private int count; } 48 Student solution

Hmmmmm… Clearly the mechanics of analyzing the data is the same in ALL cases but the details of measurement are different. BankAccount : balance Coin: value Student: gpa 49

Suppose we consider the following: public interface Measurable { double getMeasure(); } 50

Solution: //Computes the average of a set of // data values. public class DataSet { public DataSet() { sum = 0; count = 0; maximum = null; } //Adds a data value to the data // set public void add(Measurable x) { sum = sum + x.getMeasure(); if (count == 0 || maximum.getMeasure () < x.getMeasure ()) maximum = x; count++; } //Returns the average of the added data. public double getAverage() { if (count == 0) return 0; else return sum / count; } //Returns the largest of the added data // or 0 if no data has been added public Measurable getMaximum() { return maximum; } private double sum; private Measurable maximum; private int count; } 51

And… public class BankAccount implements Measurable {..... public double getMeasure() { return balance; } 52

Test class public class DataSetTest { public static void main(String[] args) { DataSet bankData = new DataSet(); bankData.add(new BankAccount(0)); bankData.add(new BankAccount(10000)); bankData.add(new BankAccount(2000)); System.out.println("Average balance = " + bankData.getAverage()); Measurable max = bankData.getMaximum(); System.out.println("Highest balance = " + max.getMeasure()); DataSet coinData = new DataSet(); coinData.add(new Coin(0.25, "quarter")); coinData.add(new Coin(0.1, "dime")); coinData.add(new Coin(0.05, "nickel")); System.out.println("Average coin value = " + coinData.getAverage()); max = coinData.getMaximum(); String name = ((Coin)max).getName(); System.out.println(name + " has the highest coin value of " + max.getMeasure()); } 53

And… public class Coin implements Measurable {..... public double getMeasure() { return value; } 54

And… public class Student implements Measurable {..... public double getMeasure() { return gpa; } 55

Using Interfaces for Callbacks Using interfaces for callbacks describes a method for improving code reusability. Limitations of Measurable interface: You can add Measurable interface only to classes under your control You can measure an object in only one way E.g., cannot analyze a set of savings accounts by both bank balance and interest rate Callback mechanism: allows a class to call back a specific method when it needs more information In previous DataSet implementation, responsibility of measuring lies with the added objects themselves 56

Using Interfaces for Callbacks (cont.) Alternative: Hand the object to be measured to a method: public interface Measurer { double measure(Object anObject); } Object is the "lowest common denominator" of all classes (classes create objects) 57

Using Interfaces for Callbacks add method asks measurer (and not the added object) to do the measuring: (here measurer is an object of type Measurer) public void add(Object x) { sum = sum + measurer.measure(x); if (count == 0 || measurer.measure(maximum) < measurer.measure(x)) maximum = x; count++; 58

Using Interfaces for Callbacks You can define measurers to take on any kind of measurement public class RectangleMeasurer implements Measurer { public double measure(Object anObject) { Rectangle aRectangle = (Rectangle) anObject; double area = aRectangle.getWidth() * aRectangle.getHeight(); return area; } Must cast from Object to Rectangle Rectangle aRectangle = (Rectangle) anObject; The RectangleMeasurer class is a helper method – its one purpose is to tell the DataSet how to measure its objects. 59

Using Interfaces for Callbacks (cont.) Pass measurer to data set constructor: Measurer m = new RectangleMeasurer(); DataSet data = new DataSet(m); data.add(new Rectangle(5, 10, 20, 30)); data.add(new Rectangle(10, 20, 30, 40));... SEE TEXT PAGE for example of this set. 60

Note that the Rectangle class is decoupled from the Measurer interface UML Diagram of Measurer Interface and Related Classes

Assignment Read Sections and do self check exercises 1-7. Read Section 9.4 and do self-check exercises Review Exercises: R9.1 – R9.4, R9.6, R9.8 All Due - See Syllabus Programming Exercises: P9.1 P9.2 and 9.4 (code as one program) P9.5 and 9.6 (code as one program) All Due - See Syllabus 62