java software solutions - unibzricci/cp/slides-2017-2018/chap10.pdf · polymorphism java software...

144
Copyright © 2012 Pearson Education, Inc. Chapter 10 Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Upload: others

Post on 10-Mar-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

Chapter 10Polymorphism

Java Software SolutionsFoundations of Program Design

Seventh Edition

John LewisWilliam Loftus

Page 2: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Polymorphism• Polymorphism is an object-oriented concept that

allows us to create versatile software designs

• Chapter 10 focuses on:– defining polymorphism and its benefits– using inheritance to create polymorphic references– using interfaces to create polymorphic references– using polymorphism to implement sorting and searching

algorithms– additional GUI components

Copyright © 2012 Pearson Education, Inc.

Page 3: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Outline

Late BindingPolymorphism via InheritancePolymorphism via Interfaces

SortingSearching

Event Processing RevisitedFile Choosers and Color ChoosersSliders

Copyright © 2012 Pearson Education, Inc.

Page 4: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Binding• Consider the following method invocation:

obj.doIt();

• 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

• However, Java defers method binding until run time -- this is called dynamic binding or late binding

Copyright © 2012 Pearson Education, Inc.

Page 5: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

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 called through a polymorphic reference can change from one invocation to the next

• All object references in Java are potentially polymorphic (for instance?)

Copyright © 2012 Pearson Education, Inc.

Page 6: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Polymorphism• Suppose we create the following reference variable:

Occupation job;

• This reference can 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

Copyright © 2012 Pearson Education, Inc.

Page 7: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Outline

Late BindingPolymorphism via InheritancePolymorphism via Interfaces

SortingSearching

Event Processing RevisitedFile Choosers and Color ChoosersSliders

Copyright © 2012 Pearson Education, Inc.

Page 8: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

References and Inheritance• An object reference (declared to be of a type X)

can refer to an object of any class related to X by inheritance

• For example, if Holiday is the superclass of Christmas, then a Holiday reference could be used to refer to a Christmas object

Holiday day;day = new Christmas();

Holiday

Christmas

Copyright © 2012 Pearson Education, Inc.

Page 9: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

References and Inheritance• These type compatibility rules are just an extension

of the is-a relationship established by inheritance

• Assigning a Christmas object to a Holiday reference is fine because Christmas is-a Holiday

• Assigning a child object to a parent reference can be performed by simple assignment

Copyright © 2012 Pearson Education, Inc.

Holiday day;day = new Christmas();

Page 10: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

References and Inheritance• Assigning a parent object to a child reference can

be done also, but must be done with a cast

• After all, Christmas is a holiday but not all holidays are Christmas

• You must know at compile time that the dayreference is actually referring to a Christmasobject.

Copyright © 2012 Pearson Education, Inc.

Holiday day = new Christmas();Christmas mas = (Christmas) day;

Page 11: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Polymorphism via Inheritance• Now suppose the Holiday class has a method

called celebrate, and Christmas overrides it

• What method is invoked by the following?Holiday day = new Christmas();day.celebrate();

• The type of the object being referenced, not the reference type, determines which method is invoked

• If day refers to a Holiday object, it invokes the Holiday version of celebrate; if it refers to a Christmas object, it invokes that version

Page 12: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Polymorphism via Inheritance• Note that the compiler restricts invocations

based on the type of the reference• So if Christmas had a method called getTree

that Holiday didn't have, the following would cause a compiler error:

Holiday day = new Christmas();day.getTree(); // compiler error

• Remember, the compiler doesn't "know" which type of holiday is being (dynamically) referenced

• A cast can be used to allow the call (if this is a method of Christmas):

((Christmas)day).getTree();

Page 13: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quick Check

Copyright © 2012 Pearson Education, Inc.

If MusicPlayer is the parent of CDPlayer, are the following assignments valid?

MusicPlayer mplayer = new CDPlayer();

CDPlayer cdplayer = new MusicPlayer();

Page 14: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quick Check

Copyright © 2012 Pearson Education, Inc.

If MusicPlayer is the parent of CDPlayer, are the following assignments valid?

MusicPlayer mplayer = new CDPlayer();

CDPlayer cdplayer = new MusicPlayer();

Yes, because a CDPlayer is-a MusicPlayer

No, you'd have to use a cast ((CDPlayer) new MusicPlayer()) and you shouldn'tknowingly assign a super class object to asubclass reference.

Page 15: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quizpublic class BaseClass {

public void methodToOverride() {

System.out.println ("I'm the BaseClass");

}

}

public class DerivedClass extends BaseClass {

public void methodToOverride() {

System.out.println ("I'm the derivedClass");

}

}

public class TestMethod {

public static void main (String args []) {

BaseClass obj1 = new BaseClass();

BaseClass obj2 = new DerivedClass();

obj1.methodToOverride();

obj2.methodToOverride();

}

}

What is this printing?

Page 16: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quizpublic class BaseClass {

public void methodToOverride() {

System.out.println ("I'm the BaseClass");

}

}

public class DerivedClass extends BaseClass {

public void methodToOverride() {

System.out.println ("I'm the derivedClass");

}

}

public class TestMethod {

public static void main (String args []) {

BaseClass obj1 = new BaseClass();

BaseClass obj2 = new DerivedClass();

obj1.methodToOverride();

obj2.methodToOverride();

}

}

What is this printing?

I'm the BaseClassI'm the DerivedClass

Page 17: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizStudent, Employee and Retired are all extended classes of Person, and all four classes have different implementations of the method getMoney Person p = new Person(...);int m1 = p.getMoney( ); // assignment 1p = new Student(...);int m2 = p.getMoney( ); // assignment 2if (m2 < 100000)

p = new Employee(...);else if (m1 > 50000)

p = new Retired(...);int m3 = p.getMoney( ); // assignment 3

getMoney is a reference to XXX's getMoney method.What is the XXX class in assignments 1, 2 and 3?

Page 18: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizPerson p = new Person(...);int m1 = p.getMoney( ); // assignment 1p = new Student(...);int m2 = p.getMoney( ); // assignment 2if (m2 < 100000)

p = new Employee(...);else if (m1 > 50000)

p = new Retired(...);int m3 = p.getMoney( ); // assignment 3

getMoney is a reference to XXX's getMoney method.What is the XXX class in assignments 1, 2 and 3? 1) Person, 2) Student, and 3) Who knows? It may be Employee, Student or Retired depending on m1 and m2 values.

Page 19: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Polymorphism via Inheritance• Consider the following class hierarchy:

StaffMember

Executive Hourly

Volunteer Employee

Copyright © 2012 Pearson Education, Inc.

Abstract Classpublic abstract double pay();

Page 20: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Polymorphism via Inheritance• Let's look at an example that pays a set of diverse

employees using a polymorphic method

• See Firm.java (containing the main)• See Staff.java (a container for staff members)• See StaffMember.java (a generic staff member)• See Volunteer.java• See Employee.java• See Executive.java• See Hourly.java

Copyright © 2012 Pearson Education, Inc.

Page 21: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Firm.java Author: Lewis/Loftus//// 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();}

}

Page 22: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Firm.java Author: Lewis/Loftus//// 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();}

}

OutputName: SamAddress: 123 Main LinePhone: 555-0469Social Security Number: 123-45-6789Paid: 2923.07-----------------------------------Name: CarlaAddress: 456 Off LinePhone: 555-0101Social Security Number: 987-65-4321Paid: 1246.15-----------------------------------Name: WoodyAddress: 789 Off RockerPhone: 555-0000Social Security Number: 010-20-3040Paid: 1169.23-----------------------------------

Output (continued)Name: DianeAddress: 678 Fifth Ave.Phone: 555-0690Social Security Number: 958-47-3625Current hours: 40Paid: 422.0-----------------------------------Name: NormAddress: 987 Suds Blvd.Phone: 555-8374Thanks!-----------------------------------Name: CliffAddress: 321 Duds LanePhone: 555-7282Thanks!-----------------------------------

Page 23: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Staff.java Author: Lewis/Loftus//// Represents the personnel staff of a particular business.//********************************************************************

public class Staff{

private StaffMember[] staffList;

//-----------------------------------------------------------------// Constructor: Sets up the list of staff members.//-----------------------------------------------------------------public Staff (){

staffList = new StaffMember[6];

continue

Page 24: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

staffList[0] = new Executive ("Sam", "123 Main Line","555-0469", "123-45-6789", 2423.07);

staffList[1] = new Employee ("Carla", "456 Off Line","555-0101", "987-65-4321", 1246.15);

staffList[2] = new Employee ("Woody", "789 Off Rocker","555-0000", "010-20-3040", 1169.23);

staffList[3] = new Hourly ("Diane", "678 Fifth Ave.","555-0690", "958-47-3625", 10.55);

staffList[4] = new Volunteer ("Norm", "987 Suds Blvd.","555-8374");

staffList[5] = new Volunteer ("Cliff", "321 Duds Lane","555-7282");

((Executive)staffList[0]).awardBonus (500.00);

((Hourly)staffList[3]).addHours (40);}

continue

Page 25: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

//-----------------------------------------------------------------// 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!"); // it is a volunteer

elseSystem.out.println ("Paid: " + amount);

System.out.println ("-----------------------------------");}

}}

Page 26: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// StaffMember.java Author: Lewis/Loftus//// Represents a generic staff member.//********************************************************************

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;

}

continue

Page 27: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

//-----------------------------------------------------------------// 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();

}

Page 28: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Volunteer.java Author: Lewis/Loftus//// 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;}

}

Page 29: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Employee.java Author: Lewis/Loftus//// Represents a general paid employee.//********************************************************************

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;

}

continue

Page 30: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

//-----------------------------------------------------------------// 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;}

}

Page 31: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Executive.java Author: Lewis/Loftus//// Represents an executive staff member, who can earn a bonus.//********************************************************************

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}

continue

Page 32: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

//-----------------------------------------------------------------// 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; // payRate + bonus

bonus = 0;

return payment;}

}

Page 33: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Hourly.java Author: Lewis/Loftus//// Represents an employee that gets paid by the hour.//********************************************************************

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;}

continue

Page 34: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

//-----------------------------------------------------------------// 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;}

continue

Page 35: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

//-----------------------------------------------------------------// Returns information about this hourly employee as a string.//-----------------------------------------------------------------public String toString(){

String result = super.toString();

result += "\nCurrent hours: " + hoursWorked;

return result;}

}

Page 36: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz• If MusicPlayer is the parent of CDPlayer, is the

following sequence of statements legal?

Copyright © 2012 Pearson Education, Inc.

MusicPlayer mplayer = new MusicPlayer();

CDPlayer cdplayer = new CDPlayer();

cdplayer = mplayer;

Page 37: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz• If MusicPlayer is the parent of CDPlayer, is the

following sequence of statements legal?

• NO because mplayer is declared to be of type MusicPlayer and cdplayer is declared to be CDPlayer and a MusicPlayer is not a CDPlayer.

Copyright © 2012 Pearson Education, Inc.

MusicPlayer mplayer = new MusicPlayer();

CDPlayer cdplayer = new CDPlayer();

cdplayer = mplayer;

Page 38: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz• If MusicPlayer is the parent of CDPlayer, is the

following sequence of statements legal?

Copyright © 2012 Pearson Education, Inc.

MusicPlayer mplayer = new MusicPlayer();

CDPlayer cdplayer = new CDPlayer();

cdplayer = (CDPlayer)mplayer;

Page 39: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz• If MusicPlayer is the parent of CDPlayer, is the

following sequence of statements legal?

• YES but you will get a run time error when you will execute that because the mplayer variable does not refer to a CDPlayer.

Copyright © 2012 Pearson Education, Inc.

MusicPlayer mplayer = new MusicPlayer();

CDPlayer cdplayer = new CDPlayer();

cdplayer = (CDPlayer)mplayer;

Page 40: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz• How is overriding related to polymorphism?

Copyright © 2012 Pearson Education, Inc.

Page 41: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz• How is overriding related to polymorphism?

• When a child class overrides the definition of a parent's method, TWO definitions of that method exist. If a polymorphic reference is used to invoke the method, then the version that is invoked is determined by the type of the object that is referenced by the polymorphic reference variable.

Copyright © 2012 Pearson Education, Inc.

Page 42: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quizpublic class Inherit {class Figure {void display() {System.out.println("F");

}}class Rectangle extends Figure {void display() {System.out.println("R");

}}class Box extends Figure {

void display() {System.out.println("B");}

}...

...Inherit() {Figure f = new Figure();Rectangle r = new Rectangle();Box b = new Box();f.display();f = r;f.display();f = b;f.display();

}

public static voidmain(String[] args) {

new Inherit();}

}

What is printed by the following code?

Page 43: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quizpublic class Inherit {class Figure {void display() {System.out.println("F");

}}class Rectangle extends Figure {void display() {System.out.println("R");

}}class Box extends Figure {

void display() {System.out.println("B");}

}...

...Inherit() {Figure f = new Figure();Rectangle r = new Rectangle();Box b = new Box();f.display();f = r;f.display();f = b;f.display();

}

public static voidmain(String[] args) {

new Inherit();}

}

What is printed by the following code? FRB

Page 44: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quizpublic class Inherit {

abstract class Stone {protected float weight = 13;protected int value = 4;abstract public String

toString( );} class Aggregate {

protected int numKind;}class Granite extends Aggregate{

Granite( ) {weight = 25; numKind = 7;

}public String toString( ) {

return "Granite: weight= " + weight + " value="+ value + " numKind="+ numKind;

}}

Inherit( ) {Granite g = new Granite( );System.out.println(g);

}

public static void main(String[ ] args) {

new Inherit( );}

}

There is a mistake in Aggregate class. This program must printGranite: weight=25.0 value=4 numKind=7What is the solution?

A) abstract class Aggregate { B) abstract class Aggregate extends Granite { C) abstract class Aggregate extends Stone { D) class Aggregate extends Stone { E) none of the above

Page 45: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quizpublic class Inherit {

abstract class Stone {protected float weight = 13;protected int value = 4;abstract public String

toString( );} class Aggregate {

protected int numKind;}class Granite extends Aggregate{

Granite( ) {weight = 25; numKind = 7;

}public String toString( ) {

return "Granite: weight= " + weight + " value="+ value + " numKind="+ numKind;

}}

Inherit( ) {Granite g = new Granite( );System.out.println(g);

}

public static void main(String[ ] args) {

new Inherit( );}

}

There is a mistake in Aggregate class. This program must printGranite: weight=25.0 value=4 numKind=7What is the solution?

A) abstract class Aggregate { B) abstract class Aggregate extends Granite { C) abstract class Aggregate extends Stone { D) class Aggregate extends Stone { E) none of the above

Page 46: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Outline

Late BindingPolymorphism via InheritancePolymorphism via Interfaces

SortingSearching

Event Processing RevisitedFile Choosers and Color ChoosersSliders

Copyright © 2012 Pearson Education, Inc.

Page 47: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Polymorphism via Interfaces• Interfaces can be used to set up polymorphic

references as well• Suppose we declare an interface called Speaker

as follows:

Copyright © 2012 Pearson Education, Inc.

public interface Speaker{

public void speak();public void announce (String str);

}

Page 48: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Polymorphism via Interfaces• An interface name can be used as the type of an

object reference variable:Speaker current;

• The current reference can be used to point to anyobject of any class that implements the Speakerinterface

• The version of speak invoked by the following line depends on the type of object that current is referencing:

current.speak();

Copyright © 2012 Pearson Education, Inc.

Page 49: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Polymorphism via Interfaces• Now 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();

Copyright © 2012 Pearson Education, Inc.

Page 50: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Polymorphism via Interfaces• As with class reference types, the compiler will

restrict invocations to methods in the interface

• For example, even if Philosopher also had a method called pontificate, the following would still cause a compiler error:

Speaker special = new Philosopher();special.pontificate(); // compiler error

• Remember, the compiler bases its rulings on the type of the reference

Copyright © 2012 Pearson Education, Inc.

Page 51: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quick Check

Copyright © 2012 Pearson Education, Inc.

Would the following statements be valid?

Speaker first = new Dog();Philosopher second = new Philosopher();second.pontificate();first = second;

Page 52: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quick Check

Copyright © 2012 Pearson Education, Inc.

Would the following statements be valid?

Speaker first = new Dog();Philosopher second = new Philosopher();second.pontificate();first = second;

Yes, all assignments and method calls arevalid as written

Page 53: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quick Check

Copyright © 2012 Pearson Education, Inc.

Would the following statements be valid?

Speaker first = new Dog();Philosopher second = new Philosopher();first = second;second.pontificate();first.pontificate();

Page 54: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quick Check

Copyright © 2012 Pearson Education, Inc.

Would the following statements be valid?

Speaker first = new Dog();Philosopher second = new Philosopher();first = second;second.pontificate();first.pontificate();

No, first is is declared to be a Speaker, so we cannot invoke the Philosopher method pontificate() though first.

Page 55: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Outline

Late BindingPolymorphism via InheritancePolymorphism via Interfaces

SortingSearching

Event Processing RevisitedFile Choosers and Color ChoosersSliders

Copyright © 2012 Pearson Education, Inc.

Page 56: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Sorting• Sorting is the process of arranging a list of items in

a particular order

• The sorting process is based on specific criteria:– sort test scores in ascending numeric order– sort a list of people alphabetically by last name

• There are many algorithms, which vary in efficiency, for sorting a list of items

• We will examine two specific algorithms: – Selection Sort– Insertion Sort

Copyright © 2012 Pearson Education, Inc.

Page 57: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Selection Sort• The strategy of Selection Sort:

– select the min value and put it in its final place in the list

– repeat for all other values

• In more detail:

– find the smallest value in the list– switch it with the value in the first position– find the next smallest value in the list– switch it with the value in the second position– repeat until all values are in their proper places

Copyright © 2012 Pearson Education, Inc.

Page 58: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Selection Sort

Copyright © 2012 Pearson Education, Inc.

Page 59: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Swapping• The processing of the selection sort algorithm

includes the swapping of two values

• Swapping requires three assignment statements and a temporary storage location

• To swap the values of first and second:

temp = first;first = second;second = temp;

Copyright © 2012 Pearson Education, Inc.

Page 60: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz• Swap the first and third entries of the array

int numbers[] = {4, 3, 2, 1};

Copyright © 2012 Pearson Education, Inc.

Page 61: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz• Swap the first and third entries of the array

int numbers[] = {4, 3, 2, 1};

int temp;temp = numbers[0];numbers[0] = numbers[2];numbers[2] = temp;

Copyright © 2012 Pearson Education, Inc.

Page 62: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Polymorphism in Sorting

• Recall that a class that implements the Comparable interface defines a compareTomethod to determine the relative order of its objects

• We can use polymorphism to develop a generic sort for any set of Comparable objects

• The sorting method accepts as a parameter an array of Comparable objects

• That way, one method can be used to sort an array of People, or Books, or whatever

Copyright © 2012 Pearson Education, Inc.

Page 63: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Selection Sort• This technique allows each class to decide for itself

what it means for one object to be less than another

• Let's look at an example that sorts an array of Contact objects

• The selectionSort method is a static method in the Sorting class

• See PhoneList.java (containing the main)• See Sorting.java• See Contact.java

Copyright © 2012 Pearson Education, Inc.

Page 64: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

public class PhoneList{

//-----------------------------------------------------------------// Creates an array of Contact objects, sorts them, then prints// them.//-----------------------------------------------------------------public static void main (String[] args){

Contact[] friends = new Contact[8];

friends[0] = new Contact ("John", "Smith", "610-555-7384");friends[1] = new Contact ("Sarah", "Barnes", "215-555-3827");friends[2] = new Contact ("Mark", "Riley", "733-555-2969");friends[3] = new Contact ("Laura", "Getz", "663-555-3984");friends[4] = new Contact ("Larry", "Smith", "464-555-3489");friends[5] = new Contact ("Frank", "Phelps", "322-555-2284");friends[6] = new Contact ("Mario", "Guzman", "804-555-9066");friends[7] = new Contact ("Marsha", "Grant", "243-555-2837");

Sorting.selectionSort(friends);

for (Contact friend : friends)System.out.println (friend);

}}

Page 65: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

public class PhoneList{

//-----------------------------------------------------------------// Creates an array of Contact objects, sorts them, then prints// them.//-----------------------------------------------------------------public static void main (String[] args){

Contact[] friends = new Contact[8];

friends[0] = new Contact ("John", "Smith", "610-555-7384");friends[1] = new Contact ("Sarah", "Barnes", "215-555-3827");friends[2] = new Contact ("Mark", "Riley", "733-555-2969");friends[3] = new Contact ("Laura", "Getz", "663-555-3984");friends[4] = new Contact ("Larry", "Smith", "464-555-3489");friends[5] = new Contact ("Frank", "Phelps", "322-555-2284");friends[6] = new Contact ("Mario", "Guzman", "804-555-9066");friends[7] = new Contact ("Marsha", "Grant", "243-555-2837");

Sorting.selectionSort(friends);

for (Contact friend : friends)System.out.println (friend);

}}

OutputBarnes, Sarah 215-555-3827Getz, Laura 663-555-3984Grant, Marsha 243-555-2837Guzman, Mario 804-555-9066Phelps, Frank 322-555-2284Riley, Mark 733-555-2969Smith, John 610-555-7384Smith, Larry 464-555-3489

Page 66: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

The static selectionSort method in the Sorting class:

Copyright © 2012 Pearson Education, Inc.

//-----------------------------------------------------------------// Sorts the specified array of objects using the selection// sort algorithm.//-----------------------------------------------------------------public static void selectionSort (Comparable[] list){

int min;Comparable temp;

for (int index = 0; index < list.length-1; index++){

min = index;for (int scan = index+1; scan < list.length; scan++)

if (list[scan].compareTo(list[min]) < 0)min = scan;

// Swap the valuestemp = list[min];list[min] = list[index];list[index] = temp;

}}

Page 67: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// Contact.java Author: Lewis/Loftus//// Represents a phone contact.//********************************************************************

public class Contact implements Comparable{

private String firstName, lastName, phone;

//-----------------------------------------------------------------// Constructor: Sets up this contact with the specified data.//-----------------------------------------------------------------public Contact (String first, String last, String telephone){

firstName = first;lastName = last;phone = telephone;

}

continue

Page 68: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

//-----------------------------------------------------------------// Returns a description of this contact as a string.//-----------------------------------------------------------------public String toString (){

return lastName + ", " + firstName + "\t" + phone;}

//-----------------------------------------------------------------// Returns a description of this contact as a string.//-----------------------------------------------------------------public boolean equals (Object other){

return (lastName.equals(((Contact)other).getLastName()) &&firstName.equals(((Contact)other).getFirstName()));

}

continue

Page 69: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

//-----------------------------------------------------------------// Uses both last and first names to determine ordering.//-----------------------------------------------------------------public int compareTo (Object other){

int result;

String otherFirst = ((Contact)other).getFirstName();String otherLast = ((Contact)other).getLastName();

if (lastName.equals(otherLast))result = firstName.compareTo(otherFirst);

elseresult = lastName.compareTo(otherLast);

return result;}

continue

Page 70: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

//-----------------------------------------------------------------// First name accessor.//-----------------------------------------------------------------public String getFirstName (){

return firstName;}

//-----------------------------------------------------------------// Last name accessor.//-----------------------------------------------------------------public String getLastName (){

return lastName;}

}

Page 71: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

public class PhoneList{

//-----------------------------------------------------------------// Creates an array of Contact objects, sorts them, then prints// them.//-----------------------------------------------------------------public static void main (String[] args){

Contact[] friends = new Contact[8];

friends[0] = new Contact ("John", "Smith", "610-555-7384");friends[1] = new Contact ("Sarah", "Barnes", "215-555-3827");friends[2] = new Contact ("Mark", "Riley", "733-555-2969");friends[3] = new Contact ("Laura", "Getz", "663-555-3984");friends[4] = new Contact ("Larry", "Smith", "464-555-3489");friends[5] = new Contact ("Frank", "Phelps", "322-555-2284");friends[6] = new Contact ("Mario", "Guzman", "804-555-9066");friends[7] = new Contact ("Marsha", "Grant", "243-555-2837");

Sorting.selectionSort(friends);

for (Contact friend : friends)System.out.println (friend);

}}

If you declare:Comparable[] friends = new Comparable[8];

will this code compile and when executed get the same result?

Page 72: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Insertion Sort• The strategy of Insertion Sort:

– pick any item and insert it into its proper place in a sorted sublist

– repeat until all items have been inserted

• In more detail:– consider the first item to be a sorted sublist (of one item)– insert the second item into the sorted sublist, shifting the

first item if needed to make room to insert the new one– insert the third item into the sorted sublist (of two items),

shifting items as necessary– repeat until all values are inserted into their proper

positions.

Copyright © 2012 Pearson Education, Inc.

Page 73: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Insertion Sort

Copyright © 2012 Pearson Education, Inc.

Page 74: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

The static insertionSort method in the Sorting class:

Copyright © 2012 Pearson Education, Inc.

//-----------------------------------------------------------------// Sorts the specified array of objects using the insertion// sort algorithm.//-----------------------------------------------------------------public static void insertionSort (Comparable[] list){

for (int index = 1; index < list.length; index++) //starting{ // from the second

Comparable key = list[index]; // value to be insertedint position = index; // position of the entry to compare with key

// Shift larger values to the rightwhile (position > 0 && key.compareTo(list[position-1]) < 0){

list[position] = list[position-1]; // shift back the largerposition--;

}

list[position] = key; // finally put key in the right position}

}

Page 75: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Comparing Sorts• The Selection and Insertion sort algorithms are

similar in efficiency

• They both have outer loops that scan all elements, and inner loops that compare the value of the outer loop with almost all values in the list

• Approximately n2 number of comparisons are made to sort a list of size n

• We therefore say that these sorts are of order n2

• Exercise: Compare the two sorts when the list is already sorted.

Copyright © 2012 Pearson Education, Inc.

Page 76: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz• Show the sequence of changes the selection and

insertion sort algorithm makes to the following array of numbers– {5 7 1 8 2 4 3}

Write the array content at every iteration of the outer loop.

Copyright © 2012 Pearson Education, Inc.

Page 77: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz• Show the sequence of changes the selection and

insertion sort algorithm makes to the following array of numbers– {5 7 1 8 2 4 3}

5 7 1 8 2 4 31 7 5 8 2 4 31 2 5 8 7 4 31 2 3 8 7 4 51 2 3 4 7 8 51 2 3 4 5 8 71 2 3 4 5 7 8

5 7 1 8 2 4 35 7 1 8 2 4 31 5 7 8 2 4 31 5 7 8 2 4 31 2 5 7 8 4 31 2 4 5 7 8 31 2 3 4 5 7 8

Selection Insertion

yellow means that the value was compared to a target (orange)

Page 78: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz• Write a static method of the class ArrayUtil that

given two sorted arrays of int returns another sorted array of int that is the merge of the input arrays.

• Example:– Input: {1, 4, 6, 8}, {3, 5}– Output: {1, 3, 4, 5, 6, 8}

– Input: {1, 4, 6, 8}, {1, 3, 5, 10}– Output: {1, 1, 3, 4, 5, 6, 8, 10}

Copyright © 2012 Pearson Education, Inc.

Page 79: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quizpublic static int[] merge(int[] a, int[] b) {

int la = a.length;int lb = b.length;int[] res = new int[la + lb];int i = 0, j = 0, k = 0;

...}

Page 80: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quizpublic static int[] merge(int[] a, int[] b) {

int la = a.length;int lb = b.length;int[] res = new int[la + lb];int i = 0, j = 0, k = 0;

while (i < la || j < lb) {if (i < la && (j < lb && a[i] < b[j] || j == lb)) {

res[k] = a[i];i++;

} else {res[k] = b[j];j++;

}k++;

}return res;

}

Page 81: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quizpublic static int[] merge(int[] a, int[] b) {

int la = a.length;int lb = b.length;int[] res = new int[la + lb];int i = 0, j = 0, k = 0;

while (i < la && j < lb) {if (a[i] < b[j]) {

res[k] = a[i]; i++;} else {

res[k] = b[j]; j++;}k++;

}if (i==la)

while (j<lb) { res[k]=b[j]; j++; k++;

}else

while (i<la) {res[k]=a[i]; i++; k++;

}return res;

}

Page 82: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Outline

Late BindingPolymorphism via InheritancePolymorphism via Interfaces

SortingSearching

Event Processing RevisitedFile Choosers and Color ChoosersSliders

Copyright © 2012 Pearson Education, Inc.

Page 83: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Searching• Searching is the process of finding a target element

within a group of items called the search pool

• The target may or may not be in the search pool

• We want to perform the search efficiently, minimizing the number of comparisons

• Let's look at two classic searching approaches: linear search and binary search

• As we did with sorting, we'll implement the searches with polymorphic Comparable parameters

Copyright © 2012 Pearson Education, Inc.

Page 84: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Linear Search• A linear search begins at one end of a list and

examines each element in turn

• Eventually, either the item is found or the end of the list is encountered

Copyright © 2012 Pearson Education, Inc.

Page 85: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Binary Search• A binary search assumes the list of items in the

search pool is sorted• It eliminates a large part of the search pool with a

single comparison

• A binary search first examines the middle element of the list -- if it matches the target, the search is over

• If it doesn't, only one half of the remaining elements need be searched

• Since they are sorted, the target can only be in one half of the other

Copyright © 2012 Pearson Education, Inc.

Page 86: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Binary Search• The process continues by comparing the middle

element of the remaining viable candidates

• Each comparison eliminates approximately half of the remaining data

• Eventually, the target is found or the data is exhausted

Copyright © 2012 Pearson Education, Inc.

Page 87: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Binary Searching: 7911 28 29 47 53 54 56 70 73 88

compare 79 with the entry in position (0+9)/2 = 4(79 == 53) ---- NO it is larger

11 28 29 47 53 54 56 70 73 88compare 79 with the entry in position (5+9)/2 = 7(79 == 70) ---- NO it is larger

11 28 29 47 53 54 56 70 73 88compare 79 with the entry in position (8+9)/2 = 8(79 == 73) ---- NO it is larger

11 28 29 47 53 54 56 70 73 88compare 79 with the entry in position (9+9)/2 = 9(79 == 88) ---- NO it is larger and there are no more entriesNOT FOUND

Page 88: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Searching• The search methods are implemented as static

methods in the Searching class

• See PhoneList2.java• See Searching.java

Copyright © 2012 Pearson Education, Inc.

Page 89: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// PhoneList2.java Author: Lewis/Loftus//// Driver for testing searching algorithms.//********************************************************************

public class PhoneList2{

//-----------------------------------------------------------------// Creates an array of Contact objects, sorts them, then prints// them.//-----------------------------------------------------------------public static void main (String[] args){

Contact test, found;Contact[] friends = new Contact[8];

friends[0] = new Contact ("John", "Smith", "610-555-7384");friends[1] = new Contact ("Sarah", "Barnes", "215-555-3827");friends[2] = new Contact ("Mark", "Riley", "733-555-2969");friends[3] = new Contact ("Laura", "Getz", "663-555-3984");friends[4] = new Contact ("Larry", "Smith", "464-555-3489");friends[5] = new Contact ("Frank", "Phelps", "322-555-2284");friends[6] = new Contact ("Mario", "Guzman", "804-555-9066");friends[7] = new Contact ("Marsha", "Grant", "243-555-2837");

continue

Page 90: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

test = new Contact ("Frank", "Phelps", "");found = (Contact) Searching.linearSearch(friends, test);if (found != null)

System.out.println ("Found: " + found);else

System.out.println ("The contact was not found.");System.out.println ();

Sorting.selectionSort(friends);

test = new Contact ("Mario", "Guzman", "");found = (Contact) Searching.binarySearch(friends, test);if (found != null)

System.out.println ("Found: " + found);else

System.out.println ("The contact was not found.");}

}

Page 91: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

test = new Contact ("Frank", "Phelps", "");found = (Contact) Searching.linearSearch(friends, test);if (found != null)

System.out.println ("Found: " + found);else

System.out.println ("The contact was not found.");System.out.println ();

Sorting.selectionSort(friends);

test = new Contact ("Mario", "Guzman", "");found = (Contact) Searching.binarySearch(friends, test);if (found != null)

System.out.println ("Found: " + found);else

System.out.println ("The contact was not found.");}

}

OutputFound: Phelps, Frank 322-555-2284

Found: Guzman, Mario 804-555-9066

Page 92: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

The linearSearch method in the Searching class:

Copyright © 2012 Pearson Education, Inc.

//-----------------------------------------------------------------// Searches the specified array of objects for the target using// a linear search. Returns a reference to the target object from// the array if found, and null otherwise.//-----------------------------------------------------------------public static Comparable linearSearch (Comparable[] list,

Comparable target){

int index = 0;boolean found = false;

while (!found && index < list.length){

if (list[index].equals(target))found = true;

elseindex++;

}

if (found)return list[index];

elsereturn null;

}

Page 93: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

The binarySearch method in the Searching class:

Copyright © 2012 Pearson Education, Inc.

public static Comparable binarySearch (Comparable[] list,Comparable target)

{int min=0, max=list.length - 1, mid=0;boolean found = false;

while (!found && min <= max) // min>max if not found{

mid = (min+max) / 2;if (list[mid].equals(target))

found = true;else

if (target.compareTo(list[mid]) < 0) // target smaller thanmax = mid-1; // entry in mid position

elsemin = mid+1;

}if (found)

return list[mid];else

return null;}

}

Page 94: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz• Given the following list of numbers, how many

elements would be examined (# of calls to equals()) by the linear search to determine if the indicated targets are on the list?– 15 21 4 17 8 27 1 22 43 57 25 7 53 12 16

• a) 17• b) 15• c) 16• d) 45

Copyright © 2012 Pearson Education, Inc.

Page 95: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz• Given the following list of numbers, how many

elements would be examined by the linear search to determine if the indicated targets are on the list?– 15 21 4 17 8 27 1 22 43 57 25 7 53 12 16

• a) 17 à 4• b) 15 à 1• c) 16 à 15• d) 45 à 15

Copyright © 2012 Pearson Education, Inc.

Page 96: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz• Given the following list of numbers, how many

elements would be examined (# of calls to equals()) by the binary search to determine if the indicated targets are on the list?

• a) 17• b) 15• c) 16• d) 45

Copyright © 2012 Pearson Education, Inc.

1 4 7 8 12 15 16 17 21 22 25 27 43 53 570 1 2 3 4 5 6 7 8 9 10 11 12 13 14

numberindex

Page 97: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz• Given the following list of numbers, how many

elements would be examined by the linear search to determine if the indicated targets are on the list?

• a) 17 à 1• b) 15 à 3• c) 16 à 4• d) 45 à 4

Copyright © 2012 Pearson Education, Inc.

1 4 7 8 12 15 16 17 21 22 25 27 43 53 570 1 2 3 4 5 6 7 8 9 10 11 12 13 14

numberindex

Page 98: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizWhat kind of performance can you expect if you perform linear search on a sorted array?

A) The performance will be about the same as on an unsorted array B) The performance will be much better than on an unsorted array C) The performance will be much worse than on an unsorted array D) The performance will be worse than n2 in this case E) none of the above

Page 99: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizWhat kind of performance can you expect if you perform linear search on a sorted array? A) The performance will be about the same as on an unsorted array B) The performance will be much better than on an unsorted array C) The performance will be much worse than on an unsorted array D) The performance will be worse than n2 in this case E) none of the above Linear search doesn't make any assumptions about whether or not its data is sorted. So, if the data happens to be sorted or not, it won't make any difference. Linear sort will perform roughly as n.

Page 100: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Outline

Late BindingPolymorphism via InheritancePolymorphism via Interfaces

SortingSearching

Event Processing RevisitedFile Choosers and Color ChoosersSliders

Copyright © 2012 Pearson Education, Inc.

Page 101: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Event Processing• Polymorphism plays an important role in the

development of a Java graphical user interface

• Consider the following code:JButton button = new JButton();button.addActionListener(new MyListener());

• Note that the addActionListener method is accepting a MyListener object as a parameter

• In fact, we can pass the addActionListenermethod any object that implements the ActionListener interface

Copyright © 2012 Pearson Education, Inc.

Page 102: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Event Processing• The code for addActionListener 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 actionPerformedmethod 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

Copyright © 2012 Pearson Education, Inc.

Page 103: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Outline

Late BindingPolymorphism via InheritancePolymorphism via Interfaces

SortingSearching

Event Processing RevisitedFile Choosers and Color ChoosersSliders

Copyright © 2012 Pearson Education, Inc.

Page 104: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Dialog Boxes• Recall that a dialog box is a small window that

"pops up" to interact with the user for a brief, specific purpose

• We used the JOptionPane class in Chapter 6 to create dialog boxes for presenting information, confirming an action, or accepting an input value

• Let's now look at two other classes that let us create specialized dialog boxes

Copyright © 2012 Pearson Education, Inc.

Page 105: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

File Choosers• Situations often arise where we want the user to

select a file stored on a disk drive, usually so that its contents can be read and processed

• A file chooser, represented by the JFileChooserclass, simplifies this process

• The user can browse the disk and filter the file types displayed

• See DisplayFile.java

Copyright © 2012 Pearson Education, Inc.

Page 106: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// DisplayFile.java Author: Lewis/Loftus//// Demonstrates the use of a file chooser and a text area.//********************************************************************

import java.util.Scanner;import java.io.*;import javax.swing.*;

public class DisplayFile{

//-----------------------------------------------------------------// Opens a file chooser dialog, reads the selected file and// loads it into a text area.//-----------------------------------------------------------------public static void main (String[] args) throws IOException{

JFrame frame = new JFrame ("Display File");frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

JTextArea ta = new JTextArea (20, 30);JFileChooser chooser = new JFileChooser();

int status = chooser.showOpenDialog (null);

continue

Page 107: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

if (status != JFileChooser.APPROVE_OPTION)ta.setText ("No File Chosen");

else{

File file = chooser.getSelectedFile();Scanner scan = new Scanner (file);

String info = "";while (scan.hasNext())

info += scan.nextLine() + "\n";

ta.setText (info);}

frame.getContentPane().add (ta);frame.pack();frame.setVisible(true);

}}

Page 108: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

if (status != JFileChooser.APPROVE_OPTION)ta.setText ("No File Chosen");

else{

File file = chooser.getSelectedFile();Scanner scan = new Scanner (file);

String info = "";while (scan.hasNext())

info += scan.nextLine() + "\n";

ta.setText (info);}

frame.getContentPane().add (ta);frame.pack();frame.setVisible(true);

}}

Page 109: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Color Choosers• In many situations we want to allow the user to

select a color

• A color chooser, represented by the JColorChooser class, simplifies this process

• The user can choose a color from a palette or specify the color using RGB values

• See DisplayColor.java

Copyright © 2012 Pearson Education, Inc.

Page 110: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// DisplayColor.java Author: Lewis/Loftus//// Demonstrates the use of a color chooser.//********************************************************************

import javax.swing.*;import java.awt.*;

public class DisplayColor{

//-----------------------------------------------------------------// Presents a frame with a colored panel, then allows the user// to change the color multiple times using a color chooser.//-----------------------------------------------------------------public static void main (String[] args){

JFrame frame = new JFrame ("Display Color");frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

JPanel colorPanel = new JPanel();colorPanel.setBackground (Color.white);colorPanel.setPreferredSize (new Dimension (300, 100));

continue

Page 111: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

frame.getContentPane().add (colorPanel);frame.pack();frame.setVisible(true);

Color shade = Color.white;int again;

do {

shade = JColorChooser.showDialog (frame, "Pick a Color!",shade); //the initial color

colorPanel.setBackground (shade);

again = JOptionPane.showConfirmDialog (null,"Display another color?");

}while (again == JOptionPane.YES_OPTION);

}}

Page 112: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

continue

frame.getContentPane().add (colorPanel);frame.pack();frame.setVisible(true);

Color shade = Color.white;int again;

do {

shade = JColorChooser.showDialog (frame, "Pick a Color!",shade);

colorPanel.setBackground (shade);

again = JOptionPane.showConfirmDialog (null,"Display another color?");

}while (again == JOptionPane.YES_OPTION);

}}

Copyright © 2012 Pearson Education, Inc.

Page 113: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Outline

Late BindingPolymorphism via InheritancePolymorphism via Interfaces

SortingSearching

Event Processing RevisitedFile Choosers and Color ChoosersSliders

Copyright © 2012 Pearson Education, Inc.

Page 114: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Sliders• A slider is a GUI component that allows the user to

specify a value within a numeric range

• A slider can be oriented vertically or horizontally and can have optional tick marks and labels

• The minimum and maximum values for the slider are set using the JSlider constructor

• A slider produces a ChangeEvent when the slider is moved, indicating that the slider and the value it represents has changed

• So you need to implement a ChangeListenerCopyright © 2012 Pearson Education, Inc.

Page 115: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Sliders• Let's look at an example that uses three sliders to

change values representing the color components of an RGB value

• See SlideColor.java

• See SlideColorPanel.java

Copyright © 2012 Pearson Education, Inc.

Page 116: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// SlideColor.java Authors: Lewis/Loftus//// Demonstrates the use slider components.//********************************************************************

import java.awt.*;import javax.swing.*;

public class SlideColor{

//-----------------------------------------------------------------// Presents up a frame with a control panel and a panel that// changes color as the sliders are adjusted.//-----------------------------------------------------------------public static void main (String[] args){

JFrame frame = new JFrame ("Slide Colors");frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

frame.getContentPane().add(new SlideColorPanel());

frame.pack();frame.setVisible(true);

}}

Page 117: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// SlideColor.java Authors: Lewis/Loftus//// Demonstrates the use slider components.//********************************************************************

import java.awt.*;import javax.swing.*;

public class SlideColor{

//-----------------------------------------------------------------// Presents up a frame with a control panel and a panel that// changes color as the sliders are adjusted.//-----------------------------------------------------------------public static void main (String[] args){

JFrame frame = new JFrame ("Slide Colors");frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

frame.getContentPane().add(new SlideColorPanel());

frame.pack();frame.setVisible(true);

}}

Page 118: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

//********************************************************************// SlideColorPanel.java Authors: Lewis/Loftus//// Represents the slider control panel for the SlideColor program.//********************************************************************

import java.awt.*;import javax.swing.*;import javax.swing.event.*;

public class SlideColorPanel extends JPanel{

private JPanel controls, colorPanel;private JSlider rSlider, gSlider, bSlider;private JLabel rLabel, gLabel, bLabel;

//-----------------------------------------------------------------// Sets up the sliders and their labels, aligning them along// their left edge using a box layout.//-----------------------------------------------------------------public SlideColorPanel(){

rSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0);rSlider.setMajorTickSpacing (50);rSlider.setMinorTickSpacing (10);rSlider.setPaintTicks (true);rSlider.setPaintLabels (true);rSlider.setAlignmentX (Component.LEFT_ALIGNMENT);

continue

Page 119: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

gSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0);gSlider.setMajorTickSpacing (50);gSlider.setMinorTickSpacing (10);gSlider.setPaintTicks (true);gSlider.setPaintLabels (true);gSlider.setAlignmentX (Component.LEFT_ALIGNMENT);

bSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0);bSlider.setMajorTickSpacing (50);bSlider.setMinorTickSpacing (10);bSlider.setPaintTicks (true);bSlider.setPaintLabels (true);bSlider.setAlignmentX (Component.LEFT_ALIGNMENT);

SliderListener listener = new SliderListener();rSlider.addChangeListener (listener);gSlider.addChangeListener (listener);bSlider.addChangeListener (listener);

rLabel = new JLabel ("Red: 0");rLabel.setAlignmentX (Component.LEFT_ALIGNMENT);gLabel = new JLabel ("Green: 0");gLabel.setAlignmentX (Component.LEFT_ALIGNMENT);bLabel = new JLabel ("Blue: 0");bLabel.setAlignmentX (Component.LEFT_ALIGNMENT);

continue

Page 120: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

controls = new JPanel();BoxLayout layout = new BoxLayout (controls, BoxLayout.Y_AXIS);controls.setLayout (layout);controls.add (rLabel);controls.add (rSlider);controls.add (Box.createRigidArea (new Dimension (0, 20)));controls.add (gLabel);controls.add (gSlider);controls.add (Box.createRigidArea (new Dimension (0, 20)));controls.add (bLabel);controls.add (bSlider);

colorPanel = new JPanel();colorPanel.setPreferredSize (new Dimension (100, 100));colorPanel.setBackground (new Color (0, 0, 0));

add (controls);add (colorPanel);

}

continue

Page 121: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Copyright © 2012 Pearson Education, Inc.

continue

//*****************************************************************// Represents the listener for all three sliders.//*****************************************************************private class SliderListener implements ChangeListener{

private int red, green, blue;

//--------------------------------------------------------------// Gets the value of each slider, then updates the labels and// the color panel.//--------------------------------------------------------------public void stateChanged (ChangeEvent event){

red = rSlider.getValue();green = gSlider.getValue();blue = bSlider.getValue();

rLabel.setText ("Red: " + red);gLabel.setText ("Green: " + green);bLabel.setText ("Blue: " + blue);

colorPanel.setBackground (new Color (red, green, blue));}

}}

Page 122: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Summary• Chapter 10 has focused on:

– defining polymorphism and its benefits– using inheritance to create polymorphic references– using interfaces to create polymorphic references– using polymorphism to implement sorting and searching

algorithms– additional GUI components

Copyright © 2012 Pearson Education, Inc.

Page 123: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizAn int array stores the following values. Use the array to answer these next questions.

Which of the following lists of numbers would accurately show the array after the first pass through the Selection Sort algorithm? A) 9, 4, 12, 2, 6, 8, 18 B) 4, 9, 12, 2, 6, 8, 18 C) 2, 4, 12, 9, 6, 8, 18 D) 2, 4, 6, 8, 9, 12, 18 E) 2, 4, 9, 12, 6, 8, 18

Copyright © 2012 Pearson Education, Inc.

Page 124: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizAn int array stores the following values. Use the array to answer these next questions.

Which of the following lists of numbers would accurately show the array after the first pass through the Selection Sort algorithm? A) 9, 4, 12, 2, 6, 8, 18 B) 4, 9, 12, 2, 6, 8, 18 C) 2, 4, 12, 9, 6, 8, 18 D) 2, 4, 6, 8, 9, 12, 18 E) 2, 4, 9, 12, 6, 8, 18

Copyright © 2012 Pearson Education, Inc.

Page 125: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizAn int array stores the following values. Use the array to answer these next questions.

Which of the following lists of numbers would accurately show the array after the fourth pass through the Selection Sort algorithm? A) 9, 4, 12, 2, 6, 8, 18 B) 2, 4, 6, 9, 12, 8, 18 C) 2, 4, 6, 8, 9, 12, 18 D) 2, 4, 6, 9, 8, 12, 18 E) 2, 4, 6, 8, 12, 9, 18

Copyright © 2012 Pearson Education, Inc.

Page 126: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizAn int array stores the following values. Use the array to answer these next questions.

Which of the following lists of numbers would accurately show the array after the fourth pass through the Selection Sort algorithm? A) 9, 4, 12, 2, 6, 8, 18 B) 2, 4, 6, 9, 12, 8, 18 C) 2, 4, 6, 8, 9, 12, 18 D) 2, 4, 6, 9, 8, 12, 18 E) 2, 4, 6, 8, 12, 9, 18

Copyright © 2012 Pearson Education, Inc.

Page 127: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quizpublic class Inherit { abstract class Speaker {abstract public void speak( );

}class Cat extends Speaker {public void speak( ){System.out.println("Woof!");

}} class Dog extends Speaker {public void speak( ){ System.out.println("Meow!");

}} ...

...Inherit( ){

Speaker d = new Dog( );Speaker c = new Cat( );d.speak( );c.speak( );

}

public static void main(String[ ]args)

{new Inherit( );

}

}

What is printed by the following code?

Page 128: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quizpublic class Inherit { abstract class Speaker {abstract public void speak( );

}class Cat extends Speaker {public void speak( ){System.out.println("Woof!");

}} class Dog extends Speaker {public void speak( ){ System.out.println("Meow!");

}} ...

...Inherit( ){

Speaker d = new Dog( );Speaker c = new Cat( );d.speak( );c.speak( );

}

public static void main(String[ ]args)

{new Inherit( );

}

}

Meow!Woof!

Page 129: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizWhich statement is completely true?

A) Java upcasts automatically, but you must explicitly downcast (upcasting = casting up in the hierarchy., .e.g., to Object)B) Java downcasts automatically, but you must explicitly upcast C) Java expects the user to explicitly upcast and downcast D) Java will both upcast and downcast automatically E) The rules for upcasting and downcasting depend upon whether classes are declared public, protected, or private

Copyright © 2012 Pearson Education, Inc.

Page 130: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizWhich statement is completely true?

A) Java upcasts automatically, but you must explicitly downcast (upcasting = casting up in the hierarchy., .e.g., to Object)B) Java downcasts automatically, but you must explicitly upcast C) Java expects the user to explicitly upcast and downcast D) Java will both upcast and downcast automatically E) The rules for upcasting and downcasting depend upon whether classes are declared public, protected, or private Upcasting is entirely safe, it's a product of the single inheritance structure that Java supports. Downcasting, by comparison, must be done explicitly by the programmer. Java only casts in one direction automatically it upcasts.

Page 131: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quiz: what does it?void arrange(float[ ] ary){

for (int n=0; n<ary.length; n++)for (int k=n; k<ary.length; k++)

if (ary[n] > ary[k]){

float x = ary[n];ary[n] = ary[k];ary[k] = x;

}}

Page 132: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

Quizvoid arrange(float[ ] ary){

for (int n=0; n<ary.length; n++)for (int k=n; k<ary.length; k++)

if (ary[n] > ary[k]){

float x = ary[n];ary[n] = ary[k];ary[k] = x;

}} It sorts the input array in ascending order

Page 133: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizCan a program exhibit polymorphism if it only implements early binding? A) Yes, because one form of polymorphism is overloading B) No, because without late binding polymorphism cannot be supported C) Yes, because so long as the programs uses inheritance and/or interfaces it supports polymorphism D) Yes, because early binding has nothing to do with polymorphism E) none of the above

Copyright © 2012 Pearson Education, Inc.

Page 134: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizCan a program exhibit polymorphism if it only implements early binding? A) Yes, because one form of polymorphism is overloading B) No, because without late binding polymorphism cannot be supported C) Yes, because so long as the programs uses inheritance and/or interfaces it supports polymorphism D) Yes, because early binding has nothing to do with polymorphism E) none of the above

While inheritance and interfaces support polymorphism, they only do so if one has late binding. But, overloading is a form of polymorphism -- one (method) name, multiple bodies -- so as long as the program uses overloading, polymorphism is in use.

Page 135: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizThe type of the reference, not the type of the object, is used to determine which version of a method is invoked in a polymorphic reference. True or False?

Copyright © 2012 Pearson Education, Inc.

Page 136: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizThe type of the reference, not the type of the object, is used to determine which version of a method is invoked in a polymorphic reference.

FalseBackwards! It is the type of the object, not the type of the reference, that determines which method is invoked .

Copyright © 2012 Pearson Education, Inc.

Page 137: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizAn interface reference can refer to any object of any class that implements the interface.

True of False?

Copyright © 2012 Pearson Education, Inc.

Page 138: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizAn interface reference can refer to any object of any class that implements the interface.

TrueThis is one of the polymorphic functions of using an interface name to declare a reference variable.

Copyright © 2012 Pearson Education, Inc.

Page 139: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizA method's parameter can be polymorphic, giving the method flexible control of its arguments.

True or False?

Copyright © 2012 Pearson Education, Inc.

Page 140: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizA method's parameter can be polymorphic, giving the method flexible control of its arguments.

TrueTo accomplish this, merely use an interface name or a base class name to declare the variable. Then the parameter is polymorphic -- referring to the correct instance of the class during execution, with the correct semantics being accessed during execution.

Copyright © 2012 Pearson Education, Inc.

Page 141: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizIs it possible to use both overloading and overriding in the same method?

True or False?

Copyright © 2012 Pearson Education, Inc.

Page 142: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizIs it possible to use both overloading and overriding in the same method?

TrueA method which is declared in a descendent class certainly can override a method in a parent class so long as the method in the parent class isn't declared final. Now, if the descendent class contains another method with the same name and different signature the new method will also overload it.

Copyright © 2012 Pearson Education, Inc.

Page 143: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizFind the errorspublic abstract class AbstractClass {

public int one() {return 1;

}public abstract int two();private abstract int three ();final abstract int four ();static abstract int five ();public abstract class Subclass extends

AbstractClass {}public class Subclass2 extends AbstractClass {

public int two() {return 2;

}protected int four() {

return 4;}

}}

Page 144: Java Software Solutions - unibzricci/CP/slides-2017-2018/Chap10.pdf · Polymorphism Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

QuizFind the errorspublic abstract class AbstractClass {

public int one() {return 1;

}public abstract int two();private abstract int three ();final abstract int four ();static abstract int five ();public abstract class Subclass extends

AbstractClass {}public class Subclass2 extends AbstractClass {

public int two() {return 2;

}protected int four() {

return 4;}

}}

abstract methods cannot be privateabstract methods cannot be finalabstract methods cannot be static

Subclass2 must be abstract because it is not implementingall the abstract methods in AbstractClass