Polymorphism Chapter 9 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.

Slides:



Advertisements
Similar presentations
Interfaces A Java interface is a collection
Advertisements

Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Inheritance and.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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
More Inheritance Abstract Classes Interfaces Briana B. Morrison CSE 1302C Spring 2010.
Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Chapter 9: Polymorphism Coming up: Binding.
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved9-2 Polymorphism Polymorphism (having many forms) is an object- oriented concept.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
1 Polymorphism Polymorphism by inheritance Polymorphism by interfaces Reading for this lecture: L&L 9.1 – 9.3.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Abstract Classes.
1 Inheritance and Polymorphism Inheritance (Continued) Polymorphism Polymorphism by inheritance Polymorphism by interfaces Reading for this lecture: L&L.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Chapter Day 22. © 2007 Pearson Addison-Wesley. All rights reserved Agenda Day 22 Problem set 4 Posted  10 problems from chapters 7 & 8  Due Nov 21 (right.
ECE122 L22: Polymorphism Using Inheritance April 26, 2007 ECE 122 Engineering Problem Solving with Java Lecture 22 Polymorphism using Inheritance.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 9 Polymorphism 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
CS 106 Introduction to Computer Science I 04 / 21 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 04 / 28 / 2010 Instructor: Michael Eckmann.
Interfaces A Java interface is a collection of constants and abstract methods with a name that looks like a class name, i.e. first letter is capitalized.
INF 523Q Chapter 5: Enhancing Classes. 2 b We can now explore various aspects of classes and objects in more detail b Chapter 5 focuses on: object references.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
Object Oriented Design and UML
CSE 501N Fall ‘09 15: Polymorphism October 22, 2009 Nick Leidenfrost.
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved Polymorphism Polymorphism is an object-oriented concept that allows.
Chapter 9: Polymorphism Coming up: Creating Objects Revisited.
© 2004 Pearson Addison-Wesley. All rights reserved November 7, 2007 Interfaces ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved Polymorphism Polymorphism is an object-oriented concept that allows.
Chapter 9 Polymorphism. Chapter Scope The role of polymorphism Dynamic binding Using inheritance for polymorphism Exploring Java interfaces in more detail.
COS 312 DAY 14 Tony Gauvin. Ch 1 -2 Agenda Questions? First Progress Report Over due – Next progress report is March 26 Assignment 4 Due Assignment 5.
© 2004 Pearson Addison-Wesley. All rights reserved April 17, 2006 Polymorphism (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING.
1 Object Oriented Design and UML Class Relationships –Dependency –Aggregation –Interfaces –Inheritance Interfaces Reading for this Lecture: L&L 6.4 – 6.5.
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
CS 106 Introduction to Computer Science I 04 / 23 / 2010 Instructor: Michael Eckmann.
1 Advanced Polymorphism Polymorphism Review Comparator Interface Sorting with Comparators Selection Sort Insertion Sort.
Chapter 9 Polymorphism. © 2004 Pearson Addison-Wesley. All rights reserved Polymorphism Polymorphism is an object-oriented concept that allows.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
ELC 310 Day 19. © 2004 Pearson Addison-Wesley. All rights reserved9-2 Agenda Questions? Capstone Proposals Overdue  4 Submitted  3 Accepted, 1 in negotiations.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
© 2004 Pearson Addison-Wesley. All rights reserved April 14, 2006 Polymorphism ComS 207: Programming I (in Java) Iowa State University, SPRING 2006 Instructor:
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Chapter 9 Polymorphism 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization that can improve reusability and system elegance.
Designing Classes Chapter 3. Contents Encapsulation Specifying Methods Java Interfaces – Writing an Interface – Implementing an Interface – An Interface.
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Interfaces. In order to work with a class, you need to understand the public methods  methods, return types,…  after you instantiate, what can you do.
1 Lecture 8 b Data Structures b Abstraction b The “Structures” package b Preconditions and postconditions b Interfaces b Polymorphism b Vector class b.
Inheritance Chapter 8 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
2/23- Interfaces Reference: Java 6.5 and 9.3. PA-4 Review Requirements PA3 – Grading Key PA4 Requirements Doc.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
COS 312 DAY 16 Tony Gauvin.
Chapter 5: Enhancing Classes
Polymorphism November 27, 2006 ComS 207: Programming I (in Java)
Chapter 9 Polymorphism.
Polymorphism.
Designing for Inheritance
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Chapter 5: Enhancing Classes
CSE 501N Fall ‘09 13: Interfaces and Multiple Representation
Chapter 9 Polymorphism.
Object-Oriented Design Part 2
Programming in C# CHAPTER 5 & 6
Presentation transcript:

Polymorphism Chapter 9 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 2 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 2 Scope Polymorphism :  The role of polymorphism  Dynamic binding  Using inheritance for polymorphism  Exploring Java interfaces in more detail  Using interfaces for polymorphism  Polymorphic design

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 3 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 3 Method Binding Consider the following method invocation: obj.MyMethod(); At some point, this invocation is bound to the definition of the method that it invokes If this binding occurred at compile time, then that line of code would call the same method every time But Java defers method binding until run time; this is called dynamic binding or late binding

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 4 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 4 Polymorphism Polymorphism literally means “having many forms” A polymorphic reference is a variable that can refer to different types of objects at different points in time The method invoked through a polymorphic reference can change from one invocation to the next All object references in Java are potentially polymorphic

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 5 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 5 Polymorphism Suppose we create the following reference variable Occupation job; Java allows this reference to point to an Occupation object, or to any object of any compatible type This compatibility can be established using inheritance or using interfaces Careful use of polymorphic references can lead to elegant, robust software designs Poor use of polymorphic references can lead to overly complex designs with lots of hidden side-effects and surprises!

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 6 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 6 References and Inheritance An object reference can refer to an object of its class, or to an object of any class related to it by inheritance For example, if the Holiday class is the parent of Christmas, then a Holiday reference could be used to point to a Christmas object Holiday special = new Christmas();

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 7 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 7 References and Inheritance Assigning a child object to a parent reference is considered to be a widening conversion, and can be performed by simple assignment Assigning an parent object to a child reference can be done also, but it is considered a narrowing conversion and must be done with a cast The widening conversion is the most useful Remember that Inheritance creates an Is-A relationship While every Car is-a Vehicle, not all Vehicles is-a Car. Assigning a parent object Vehicle to a child Car violates the Is-A relationship Thus, this narrowing assignment seldom makes sense

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 8 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 8 Polymorphism via Inheritance It is the type of the object being referenced, not the reference type, that determines which method is invoked Suppose the Mammal class has a method called move, and the Horse class overrides it Now consider the following invocation pet.move(); If pet refers to: a Mammal object, this invokes the Mammal version of move a Horse object, this invokes the Horse version of move

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 9 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 9 Let’s look at an example that pays a set of employees using a polymorphic method Pay employees using a polymorphic method

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 10 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 10 //******************************************************************** // Firm.java Java Foundations // // Demonstrates polymorphism via inheritance. //******************************************************************** public class Firm { // // Creates a staff of employees for a firm // and pays them. // public static void main(String[] args) { Staff personnel = new Staff(); personnel.payday(); } Firm.main Creates New Staff and Pays Them

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 11 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 11 public class Staff { private StaffMember[] staffList; // Constructor: Sets up the list of staff members. public Staff() { staffList = new StaffMember[6]; staffList[0] = new Executive("Tony", "123 Main Line", " ", " ", ); staffList[1] = new Employee ("Paulie", "456 Off Line", " ", " ", ); staffList[2] = new Employee ("Vito", "789 Off Rocker", " ", " ", ); staffList[3] = new Hourly ("Michael", "678 Fifth Ave.", " ", " ", ); staffList[4] = new Volunteer("Adrianna", "987 Babe Blvd.", " "); staffList[5] = new Volunteer("Benny", "321 Dud Lane", " "); ((Executive)staffList[0]).awardBonus(500.00); ((Hourly)staffList[3]).addHours(40); } // Pays all staff members. public void payday() { double amount; for (int count=0; count < staffList.length; count++) { System.out.println (staffList[count]); amount = staffList[count].pay(); // polymorphic if (amount == 0.0) System.out.println("Thanks!"); else System.out.println("Paid: " + amount); System.out.println(" "); } Staff Creates staffList and invokes pay method

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 12 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 12 abstract public class StaffMember { protected String name; protected String address; protected String phone; // // Constructor: Sets up this staff member using the specified // information. // public StaffMember(String eName, String eAddress, String ePhone) { name = eName; address = eAddress; phone = ePhone; } // // Returns a string including the basic employee information. // public String toString() { String result = "Name: " + name + "\n"; result += "Address: " + address + "\n"; result += "Phone: " + phone; return result; } // // Derived classes must define the pay method for each type of // employee. // public abstract double pay(); } StaffMember provides Abstract Method Pay()

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 13 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 13 //******************************************************************** // Volunteer.java Java Foundations // // Represents a staff member that works as a volunteer. //******************************************************************** public class Volunteer extends StaffMember { // // Constructor: Sets up this volunteer using the specified // information. // public Volunteer(String eName, String eAddress, String ePhone) { super(eName, eAddress, ePhone); } // // Returns a zero pay value for this volunteer. // public double pay() { return 0.0; } Volunteer’s Pay() method always returns $0.00

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 14 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 14 public class Employee extends StaffMember { protected String socialSecurityNumber; protected double payRate; // // Constructor: Sets up this employee with the specified // information. // public Employee(String eName, String eAddress, String ePhone, String socSecNumber, double rate) { super(eName, eAddress, ePhone); socialSecurityNumber = socSecNumber; payRate = rate; } // // Returns information about an employee as a string. // public String toString() { String result = super.toString(); result += "\nSocial Security Number: " + socialSecurityNumber; return result; } // // Returns the pay rate for this employee. // public double pay() { return payRate; } } Employee’s Pay() method

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 15 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 15 public class Executive extends Employee { private double bonus; // // Constructor: Sets up this executive with the specified // information. // public Executive(String eName, String eAddress, String ePhone, String socSecNumber, double rate) { super(eName, eAddress, ePhone, socSecNumber, rate); bonus = 0; // bonus has yet to be awarded } // // Awards the specified bonus to this executive. // public void awardBonus(double execBonus) { bonus = execBonus; } // // Computes and returns the pay for an executive, which is the // regular employee payment plus a one-time bonus. // public double pay() { double payment = super.pay() + bonus; bonus = 0; return payment; } Executive’s Pay() method is Pay + Bonus

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 16 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 16 public class Hourly extends Employee { private int hoursWorked; // // Constructor: Sets up this hourly employee using the // specified information. // public Hourly(String eName, String eAddress, String ePhone, String socSecNumber, double rate) { super(eName, eAddress, ePhone, socSecNumber, rate); hoursWorked = 0; } // // Adds the specified number of hours to this employee's // accumulated hours. // public void addHours(int moreHours) { hoursWorked += moreHours; } // // Computes and returns the pay for this hourly employee. // public double pay() { double payment = payRate * hoursWorked; hoursWorked = 0; return payment; } Hourly employees Pay()

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 17 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 17 Pay is an abstract Polymorphic Method Staff.Payday() invokes abstract method Pay() for each staff member: amount = staffList[i].pay(); Which Pay() method is invoked based on the class of each Array element: StaffMember staffList[i] public class Hourly extends Employee public double pay() { double payment = payRate * hoursWorked; hoursWorked = 0; return payment; } public class Volunteer extends StaffMember public double pay() { return 0.0; } public class Executive extends Employee public double pay() { double payment = super.pay() + bonus; bonus = 0; return payment; } Hourly Employee public class Employee extends StaffMember public double pay() { return payRate; } Volunteer Executive

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 18 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 18 Interfaces A Java interface is a collection of abstract methods and constants An abstract method is a method header without a method body An abstract method can be declared using the modifier abstract, but because all methods in an interface are abstract, usually it is left off An interface is used to establish a set of methods that a class will implement

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 19 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 19 Interfaces public interface Doable { public void doThis(); public int doThat(); public void doThis2(float value, char ch); public boolean doTheOther(int num); } interface is a reserved word None of the methods in an interface are given a definition (body) A semicolon immediately follows each method header

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 20 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 20 Interfaces An interface cannot be instantiated Methods in an interface have public visibility by default A class formally implements an interface by stating so in the class header providing implementations for each abstract method in the interface If a class states that it implements an interface, it must define all methods in the interface

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 21 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 21 public interface Doable { public void doThis(); public int doThat(); etc. } Interfaces public class CanDo implements Doable { public void doThis () { // whatever } public void doThat () { // whatever } // etc. } implements is a reserved word Each method listed in Doable is given a definition

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 22 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 22 Interfaces A class that implements an interface can implement other methods as well In addition to (or instead of) abstract methods, an interface can contain constants When a class implements an interface, it gains access to all its constants

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 23 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 23 Interfaces Enable true Encapsulation Our class definitions, so far, include private data and methods That’s how most programmers write their Classes But that violates encapsulation because the programmer: Views private definitions in your class while looking for public ones Will see implementation details that should remain hidden Java Interfaces provide true encapsulation by: Presenting only the public information to the reader of the interface All implementation details and private variables remain hidden Can create a hierarchy of interfaces for different sets of users

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 24 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 24 //******************************************************************** // Encryptable.java Java Foundations // // Represents the interface for an object that can be encrypted // and decrypted. //******************************************************************** public interface Encryptable { public void encrypt(); public String decrypt(); } Interface Example: Encryptable Notice: Interfaces contains no private data or private methods

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 25 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 25 //******************************************************************** // Secret.java Java Foundations // // Represents a secret message that can be encrypted and decrypted. //******************************************************************** import java.util.Random; public class Secret implements Encryptable { private String message; private boolean encrypted; private int shift; private Random generator; // // Constructor: Stores the original message and establishes // a value for the encryption shift. // public Secret(String msg) { message = msg; encrypted = false; generator = new Random(); shift = generator.nextInt(10) + 5; } Secret implements Encryptable Interface public interface Encryptable { public void encrypt(); public String decrypt(); }

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 26 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 26 // // Encrypts this secret using a Caesar cipher. Has no effect if // this secret is already encrypted. // public void encrypt() { if (!encrypted) { String masked = ""; for (int index=0; index < message.length(); index++) masked = masked + (char)(message.charAt(index)+shift); message = masked; encrypted = true; } // // Decrypts and returns this secret. Has no effect if this // secret is not currently encrypted. // public String decrypt() { if (encrypted) { String unmasked = ""; for (int index=0; index < message.length(); index++) unmasked = unmasked + (char)(message.charAt(index)-shift); message = unmasked; encrypted = false; } return message; } Secret implements Encryptable Interface public interface Encryptable { public void encrypt(); public String decrypt(); }

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 27 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 27 // // Returns true if this secret is currently encrypted. // public boolean isEncrypted() { return encrypted; } // // Returns this secret (may be encrypted). // public String toString() { return message; } } Secret can implement other APIs as well…

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 28 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 28 //******************************************************************** // SecretTest.java Java Foundations // // Demonstrates the use of a formal interface. //******************************************************************** public class SecretTest { // // Creates a Secret object and exercises its encryption. // public static void main(String[] args) { Secret hush = new Secret("Harry Potter is my hero!"); System.out.println(hush); hush.encrypt(); System.out.println(hush); hush.decrypt(); System.out.println(hush); } SecretTest – Encrypt/Decrypt a Message Harry Potter is my hero! Pizz?(Xw||mz(q{(u?(pmzw) Harry Potter is my hero!

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 29 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 29 Interfaces In UML, a dotted arrow is used to show that a class implements an interface The designation > is used to indicate an interface

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 30 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 30 Interfaces A class can implement multiple interfaces The interfaces are listed in the implements clause The class must implement all methods in all interfaces listed in the header class ManyThings implements Interface1, Interface2 { // all methods of both interfaces }

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 31 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 31 Interfaces The Java API contains many helpful interfaces The Comparable interface contains one abstract method called compareTo, which is used to compare two objects We discussed the compareTo method of the String class in Chapter 4 The String class implements Comparable, giving us the ability to put strings in lexicographic order

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 32 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 32 The Comparable Interface Any class can implement Comparable to provide a mechanism for comparing objects of that type if (obj1.compareTo(obj2) < 0) System.out.println("obj1 is less than obj2"); The value returned from compareTo should be negative is obj1 is less that obj2, 0 if they are equal, and positive if obj1 is greater than obj2 When you design a class that implements the Comparable interface, it should follow this intent

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 33 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 33 The Comparable Interface It’s up to the programmer to determine what makes one object less than another For example, you may define the compareTo method of an Employee class to order employees by name (alphabetically) or by employee number The implementation of the method can be as straightforward or as complex as needed for the situation

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 34 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 34 The Iterator Interface As we discussed in Chapter 4, an iterator is an object that provides a means of processing a collection of objects one at a time An iterator is created formally by implementing the Iterator interface, which contains three methods The hasNext method returns a boolean result – true if there are items left to process The next method returns the next object in the iteration The remove method removes the object most recently returned by the next method

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 35 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 35 The Iterator Interface By implementing the Iterator interface, a class formally establishes that objects of that type are iterators The programmer must decide how best to implement the iterator functions Once established, the for-each version of the for loop can be used to process the items in the iterator

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 36 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 36 Interfaces You could write a class that implements certain methods (such as compareTo ) without formally implementing the interface ( Comparable ) However, formally establishing the relationship between a class and an interface allows Java to deal with an object in certain ways Which brings us back to polymorphism

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 37 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 37 References and Interfaces Suppose we have an interface called Speaker : public interface Speaker { public void speak(); public void announce(String str); } The interface name can now be used as the type of a reference variable: Speaker current; The variable current can now point to any object of any class that implements Speaker

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 38 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 38 Polymorphism via Interfaces The version of speak that the following line invokes depends on the type of object that current is referencing: current.speak(); This is analogous to the technique for polymorphism using inheritance

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 39 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 39 Polymorphism via Interfaces Suppose two classes, Philosopher and Dog, both implement the Speaker interface, providing distinct versions of the speak method In the following code, the first call to speak invokes one version and the second invokes another: Speaker guest = new Philospher(); guest.speak(); guest = new Dog(); guest.speak(); I think, therefore I am! Bark!

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 40 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 40 Event Processing Polymorphism plays an important role in the development of a Java graphical user interface (GUI) As we will see later, we establish a relationship between a GUI component and a listener: JButton button = new JButton(); button.addActionListener(new MyListener()); Note that the addActionListener method is accepting a MyListener object as a parameter We can pass any object that implements the ActionListener interface to the addActionListener method

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 41 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 41 Event Processing The source code for the addActionListener method accepts a parameter of type ActionListener (the interface) Because of polymorphism, any object that implements that interface is compatible with the parameter reference variable The component can call the actionPerformed method because of the relationship between the listener class and the interface Extending an adapter class to create a listener represents the same situation; the adapter class implements the appropriate interface already

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 42 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 42 Key Things to take away: Polymorphism The term polymorphism literally means “having many forms” A polymorphic reference is a variable that can refer to different types of objects at different points in time The method invoked through a polymorphic reference can change from one invocation to the next It is the type of the object being referenced, not the reference type, that determines which method is invoked Interfaces allow true encapsulation and hide implementation details Object references can be declared using an Interface name as its type Invoking Object’s method declared as an Interface use dynamic binding to invoke the method specific to the Object class, not the Reference class. Interfaces are critical for supporting GUIs and other functions cleanly

Slides based on Java Foundations 3rd Edition, Lewis/DePasquale/Chase 43 Scott Kristjanson – CMPT 125/126 – SFU Wk07.3 Slide 43 References: 1.J. Lewis, P. DePasquale, and J. Chase., Java Foundations: Introduction to Program Design & Data Structures. Addison-Wesley, Boston, Massachusetts, 3rd edition, 2014, ISBN