1 5 ObjectOriented Programming Polymorphism 1992 2007 Pearson
1 5 Object-Oriented Programming: Polymorphism 1992 -2007 Pearson Education, Inc. All rights reserved.
2 OBJECTIVES In this chapter you will learn: § The concept of polymorphism. § To use overridden methods to effect polymorphism. § To distinguish between abstract and concrete classes. § To declare abstract methods to create abstract classes. § How polymorphism makes systems extensible and maintainable. § To determine an object's type at execution time. § To declare and implement interfaces. 1992 -2007 Pearson Education, Inc. All rights reserved.
3 5. 1 5. 2 5. 3 5. 4 5. 5 5. 6 Introduction Polymorphism Examples Demonstrating Polymorphic Behavior Abstract Classes and Methods Case Study: Payroll System Using Polymorphism 5. 5. 1 Creating Abstract Superclass Employee 5. 5. 2 Creating Concrete Subclass Salaried. Employee 5. 5. 3 Creating Concrete Subclass Hourly. Employee 5. 5. 4 Creating Concrete Subclass Commission. Employee 5. 5. 5 Creating Indirect Concrete Subclass Base. Plus. Commission. Employee 5. 5. 6 Demonstrating Polymorphic Processing, Operator instanceof and Downcasting 5. 5. 7 Summary of the Allowed Assignments Between Superclass and Subclass Variables final Methods and Classes 1992 -2007 Pearson Education, Inc. All rights reserved.
4 5. 7 5. 8 50. 9 10. 10 Case Study: Creating and Using Interfaces 5. 7. 1 Developing a Payable Hierarchy 5. 7. 2 Declaring Interface Payable 5. 7. 3 Creating Class Invoice 5. 7. 4 Modifying Class Employee to Implement Interface Payable 5. 7. 5 Modifying Class Salaried. Employee for Use in the Payable Hierarchy 5. 7. 6 Using Interface Payable to Process Invoices and Employees Polymorphically 5. 7. 7 Declaring Constants with Interfaces 5. 7. 8 Common Interfaces of the Java API (Optional) GUI and Graphics Case Study: Drawing with Polymorphism (Optional) Software Engineering Case Study: Incorporating Inheritance into the ATM System Wrap-Up 1992 -2007 Pearson Education, Inc. All rights reserved.
5 5. 1 Introduction • Polymorphism – Enables “programming in the general” – The same invocation can produce “many forms” of results • Interfaces – Implemented by classes to assign common functionality to possibly unrelated classes 1992 -2007 Pearson Education, Inc. All rights reserved.
6 5. 2 Polymorphism Examples • Polymorphism – When a program invokes a method through a superclass variable, the correct subclass version of the method is called, based on the type of the reference stored in the superclass variable – The same method name and signature can cause different actions to occur, depending on the type of object on which the method is invoked – Facilitates adding new classes to a system with minimal modifications to the system’s code 1992 -2007 Pearson Education, Inc. All rights reserved.
7 5. 2 Polymorphism Examples • Animal – superclass • Dog, Cat, Fish – subclasses • Superclass has a move method or a speak method • Each subclass implements these methods differently 1992 -2007 Pearson Education, Inc. All rights reserved.
8 5. 2 Polymorphism Examples • The same method name and signature can cause different actions to occur, depending on the type of object on which the method is invoked • Call the move method on a superclass object Animal animal = new Animal(); // animal is a superclass object Dog dog = new Dog(); // dog is a subclass object animal = dog // A superclass variable – animal – refers to a subclass referance or objcet a dog objcect animal. move(); // dog’s move method is inveked Cat cat = new Cat(); // animal = cat animal. move(); // cat’s move method is inveked 1992 -2007 Pearson Education, Inc. All rights reserved.
9 5. 2 Polymorphism Examples • Facilitates adding new classes to a system with minimal modifications to the system’s code • New animals can be added to the program – The main body does not change • Add Bird class • Iterate over different animals – his code is the main code of the program which needs little modification 1992 -2007 Pearson Education, Inc. All rights reserved.
10 Software Engineering Observation 5. 1 Polymorphism enables programmers to deal in generalities and let the execution-time environment handle the specifics. Programmers can command objects to behave in manners appropriate to those objects, without knowing the types of the objects (as long as the objects belong to the same inheritance hierarchy). 1992 -2007 Pearson Education, Inc. All rights reserved.
11 Software Engineering Observation 5. 2 Polymorphism promotes extensibility: Software that invokes polymorphic behavior is independent of the object types to which messages are sent. New object types that can respond to existing method calls can be incorporated into a system without requiring modification of the base system. Only client code that instantiates new objects must be modified to accommodate new types. 1992 -2007 Pearson Education, Inc. All rights reserved.
5. 3 Demonstrating Polymorphic Behavior 12 • A super class reference can be aimed at a subclass object – This is possible because a subclass object is a superclass object as well – When invoking a method from that reference, the type of the actual referenced object, not the type of the reference, determines which method is called • A subclass reference can be aimed at a superclass object only if the object is downcasted 1992 -2007 Pearson Education, Inc. All rights reserved.
5. 3 Demonstrating Polymorphic Behavior 13 • Four possibilities • superclass – subclass • Commission. Employee – super class Base. Plus. Commission. Employee – subclass Commission. Employee commussion. Employee; Base. Plus. Commission. Employee base. Plus. Commission. Employee; commussion. Employee. to. String(); – to. String method of a super class on super class variable • base. Plus. Commussion. Employee. to. String(); – to. String method of a subclass on subclass variable 1992 -2007 Pearson Education, Inc. All rights reserved.
5. 3 Demonstrating Polymorphic Behavior 14 commission. Employee = base. Plus. Commission. Employee; • A subclass reference is assigned to a super class variable; – is it allowed? – yes – is a relation between classes – A Base. Plus. Commission. Employee is a Commission. Employee • A Commission. Emloyee type variable refers to a Base. Plus. Commission. Employee type object in memory 1992 -2007 Pearson Education, Inc. All rights reserved.
5. 3 Demonstrating Polymorphic Behavior 15 • After such an assignment commission. Employee. to. String(); • invokes the to. String method of the Base. Plus. Commission. Emloyee object in memory • But commission. Employee. get. Base. Salary(); – is not allowed – Cannot call a subclass only method on a super class varaible 1992 -2007 Pearson Education, Inc. All rights reserved.
5. 3 Demonstrating Polymorphic Behavior commission. Emloyee 16 Base. Plus. Commission. Emloyee object in memory Name, last. Name, ssn Gross. Sales, commission. Rate Base. Salary Call super calss only methods such as commision. Employee. get. Name(); commission. Emloyee. set. Ssn(“ 222 -222”); commission. Emloyee. to. String(); - to. String method of the Base. Plus. Commission. Emloyee obect is invoked 1992 -2007 Pearson Education, Inc. All rights reserved.
5. 3 Demonstrating Polymorphic Behavior base. Pluscommission. Emloyee 17 Commission. Emloyee object in memory Name, last. Name, ssn Gross. Sales, commission. Rate This assignmet is not possible withodt a casting Called downcasting A Commission. Emloyee is not a Base. Plus. Commision. Emloyee in general 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 18 Polymorphism. Test. java (1 of 2) Typical reference assignments 1992 -2007 Pearson Education, Inc. All rights reserved.
19 Assign a reference to a Outline base. Plus. Commission. Employee object to a Commission. Employee 3 variable Polymorphism. Test. java Polymorphically call base. Plus. Commission. Employee’s to. String method (2 of 2) 1992 -2007 Pearson Education, Inc. All rights reserved.
20 class - Polymorphisim. Test 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public class Polymorphism. Test { public static void main( String args[] ) { // assign superclass reference to superclass variable Commission. Employee commission. Employee = new Commission. Employee( "Sue", "Jones", "222 -22 -2222", 10000, . 06 ); // assign subclass reference to subclass variable Base. Plus. Commission. Employee 4 base. Plus. Commission. Employee = new Base. Plus. Commission. Employee( "Bob", "Lewis", "333 -33 -3333", 5000, . 04, 300 ); // invoke to. String on superclass object using superclass variable System. out. printf( "%s %s: nn%snn", "Call Commission. Employee 3's to. String with superclass reference " , "to superclass object", commission. Employee. to. String() ); 1992 -2007 Pearson Education, Inc. All rights reserved.
21 class – Polymorphisim. Test (cont) 23 // invoke to. String on subclass object using subclass variable 24 System. out. printf( "%s %s: nn%snn", 25 "Call Base. Plus. Commission. Employee 4's to. String with subclass", 26 "reference to subclass object", 27 base. Plus. Commission. Employee. to. String() ); 29 // invoke to. String on subclass object using superclass variable 30 Commission. Employee commission. Employee 2 = 31 base. Plus. Commission. Employee; 32 System. out. printf( "%s %s: nn%sn", 33 "Call Base. Plus. Commission. Employee 4's to. String with superclass", 34 "reference to subclass object", commission. Employee 2. to. String() ); 35 } // end main 36 } // end class Polymorphism. Test 1992 -2007 Pearson Education, Inc. All rights reserved.
22 output Call Commission. Employee 3's to. String with superclass reference to superclass object: commission employee: Sue Jones social security number: 222 -22 -2222 gross sales: 10000. 00 commission rate: 0. 06 Call Base. Plus. Commission. Employee 4's to. String with subclass reference to subclass object: base-salaried commission employee: Bob Lewis social security number: 333 -33 -3333 gross sales: 5000. 00 commission rate: 0. 04 base salary: 300. 00 Call Base. Plus. Commission. Employee 4's to. String with superclass reference to subclass object: base-salaried commission employee: Bob Lewis social security number: 333 -33 -3333 gross sales: 5000. 00 commission rate: 0. 04 base salary: 300. 00 1992 -2007 Pearson Education, Inc. All rights reserved.
23 Explanation Commission. Employee commission. Employee 2 = base. Plus. Commission. Employee; • A Commissio. Employee 3 type object is created – commission. Employee 2 – a super class object • it is refered to a subclass objcet it refers to what a subclass object base. Plus. Commissin. Employee points • a superclass object can reference to a subclass object because – the relation between them - is a – relation – a Base. Plus. Commission. Employee is a Commission. Emplıyee 1992 -2007 Pearson Education, Inc. All rights reserved.
24 5. 4 Abstract Classes and Methods • Abstract classes – Classes that are too general to create real objects – Used only as abstract superclasses for concrete subclasses and to declare reference variables – Many inheritance hierarchies have abstract superclasses occupying the top few levels – Keyword abstract • Use to declare a class abstract • Also use to declare a method abstract – Abstract classes normally contain one or more abstract methods – All concrete subclasses must override all inherited abstract methods 1992 -2007 Pearson Education, Inc. All rights reserved.
5. 4 Abstract Classes and Methods (Cont. ) 25 • Iterator class – Traverses all the objects in a collection, such as an array – Often used in polymorphic programming to traverse a collection that contains references to objects from various levels of a hierarchy 1992 -2007 Pearson Education, Inc. All rights reserved.
26 Abstract Classes • An abstract class typically contains one or more abstract methods – that subclasses must override if the subclasses are to be concrete. • The instance variables and concrete methods of an abstract class are subject to the normal rules of inheritance. 1992 -2007 Pearson Education, Inc. All rights reserved.
27 Software Engineering Observation 5. 3 An abstract class declares common attributes and behaviors of the various classes in a class hierarchy. An abstract class typically contains one or more abstract methods that subclasses must override if the subclasses are to be concrete. The instance variables and concrete methods of an abstract class are subject to the normal rules of inheritance. 1992 -2007 Pearson Education, Inc. All rights reserved.
28 Common Programming Error 5. 1 Attempting to instantiate an object of an abstract class is a compilation error. 1992 -2007 Pearson Education, Inc. All rights reserved.
29 Common Programming Error 5. 2 Failure to implement a superclass’s abstract methods in a subclass is a compilation error unless the subclass is also declared abstract. 1992 -2007 Pearson Education, Inc. All rights reserved.
30 Fig. 10. 2 | Employee hierarchy UML class diagram. 1992 -2007 Pearson Education, Inc. All rights reserved.
31 Fig. 9. 3 | Inheritance hierarchy for Shapes. 1992 -2007 Pearson Education, Inc. All rights reserved.
32 Abstract class example • Two. Dimensional. Shape is an abstract class • Can have an abstract area() method – Not implemented in Two. Dimensional. Shape class – Every concrete subclass of Two. Dimensional. Shape must implement area() – Cannot create objects from abstract classes – Can call static methods 1992 -2007 Pearson Education, Inc. All rights reserved.
33 Software Engineering Observation 5. 4 A subclass can inherit “interface” or “implementation” from a superclass. Hierarchies designed for implementation inheritance tend to have their functionality high in the hierarchy—each new subclass inherits one or more methods that were implemented in a superclass, and the subclass uses the superclass implementations. (cont…) 1992 -2007 Pearson Education, Inc. All rights reserved.
34 Software Engineering Observation 5. 4 Hierarchies designed for interface inheritance tend to have their functionality lower in the hierarchy—a superclass specifies one or more abstract methods that must be declared for each concrete class in the hierarchy, and the individual subclasses override these methods to provide subclass-specific implementations. 1992 -2007 Pearson Education, Inc. All rights reserved.
5. 5. 1 Creating Abstract Superclass Employee 35 • abstract superclass Employee – earnings is declared abstract • No implementation can be given for earnings in the Employee abstract class – An array of Employee variables will store references to subclass objects • earnings method calls from these variables will call the appropriate version of the earnings method 1992 -2007 Pearson Education, Inc. All rights reserved.
36 Fig. 10. 3 | Polymorphic interface for the Employee hierarchy classes. 1992 -2007 Pearson Education, Inc. All rights reserved.
37 class - Employee • An abstract class – three instance variables • first. Name, last. Name, ssn – a three parameter constructor – get and set methods for the instance variables – to. String method for getting the string representation of the object – An abstract method – earnings() • not implemented • subclasses of employee has to implement this method 1992 -2007 Pearson Education, Inc. All rights reserved.
38 class - Employee 4 5 6 7 8 9 10 11 12 13 14 15 16 public abstract class Employee { protected String first. Name; protected String last. Name; protected String social. Security. Number; // three-argument constructor public Employee( String first, String last, String ssn ) { first. Name = first; last. Name = last; social. Security. Number = ssn; } // end three-argument Employee constructor 1992 -2007 Pearson Education, Inc. All rights reserved.
39 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 // set first name public void set. First. Name( String first ) { first. Name = first; } // end method set. First. Name // return first name public String get. First. Name() { return first. Name; } // end method get. First. Name // set last name public void set. Last. Name( String last ) { last. Name = last; } // end method set. Last. Name // return last name public String get. Last. Name() { return last. Name; } // end method get. Last. Name 1992 -2007 Pearson Education, Inc. All rights reserved.
40 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 // set social security number public void set. Social. Security. Number( String ssn ) { social. Security. Number = ssn; // should validate } // end method set. Social. Security. Number // return social security number public String get. Social. Security. Number() { return social. Security. Number; } // end method get. Social. Security. Number // return String representation of Employee object public String to. String() { return String. format( "%s %snsocial security number: %s", get. First. Name(), get. Last. Name(), get. Social. Security. Number() ); } // end method to. String // abstract method overridden by subclasses public abstract double earnings(); // no implementation here } // end abstract class Employee 1992 -2007 Pearson Education, Inc. All rights reserved.
41 class - Salaried. Employee • Extends class Employee – instanece variable salary – should implement earnings method • returns the salary of the employee – A four parameter constructor • calls super class constructor as the first statement • set the additional variable salary using a set. Weekly. Salary method – to. String method overrides Employee’s to. String method • calls super’s to. String method using the keyword super 1992 -2007 Pearson Education, Inc. All rights reserved.
42 class - Salaried. Employee 4 5 6 7 8 9 public class Salaried. Employee extends Employee { private double weekly. Salary; 11 12 // four-argument constructor public Salaried. Employee( String first, String last, String ssn, double salary ) { super( first, last, ssn ); // pass to Employee constructor 13 set. Weekly. Salary( salary ); // validate and store salary 14 15 16 17 18 19 20 } // end four-argument Salaried. Employee constructor // set salary public void set. Weekly. Salary( double salary ) { weekly. Salary = salary < 0. 0 ? 0. 0 : salary; } // end method set. Weekly. Salary 1992 -2007 Pearson Education, Inc. All rights reserved.
43 class – Salaried. Employee (cont) 22 23 24 25 26 27 28 // return salary public double get. Weekly. Salary() { return weekly. Salary; } // end method get. Weekly. Salary 29 public double earnings() 30 { 31 32 33 34 35 36 37 38 39 40 // calculate earnings; override abstract method earnings in Employee return get. Weekly. Salary(); } // end method earnings // return String representation of Salaried. Employee object public String to. String() { return String. format( "salaried employee: %sn%s: $%, . 2 f", super. to. String(), "weekly salary", get. Weekly. Salary() ); } // end method to. String } // end class Salaried. Employee 1992 -2007 Pearson Education, Inc. All rights reserved.
44 class - Hourly. Employee • Extends class Employee – instanece variable wage, hours – should implement earnings method • returns wages times number of hours worked of the employee if hours < 40 or for excess hours 1. 5 * wage – A fife parameter constructor • calls super class constructor as the first statement • set the additional variables wage, hours using a set. Wage and Set. Hours method – to. String method overrides Employee’s to. String method • calls super’s to. String method using the keyword super 1992 -2007 Pearson Education, Inc. All rights reserved.
45 class - Hourly. Employee 4 5 6 7 8 9 10 12 13 14 15 16 17 public class Hourly. Employee extends Employee { private double wage; // wage per hour private double hours; // hours worked for week // five-argument constructor public Hourly. Employee( String first, String last, String ssn, double hourly. Wage, double hours. Worked { super( first, last, ssn ); set. Wage( hourly. Wage ); // validate hourly wage set. Hours( hours. Worked ); // validate hours worked } // end five-argument Hourly. Employee constructor 1992 -2007 Pearson Education, Inc. All rights reserved.
46 class – Hourly. Employee (cont) 18 19 20 21 22 23 24 25 26 27 28 30 31 // set wage public void set. Wage( double hourly. Wage ) { wage = ( hourly. Wage < 0. 0 ) ? 0. 0 : hourly. Wage; } // end method set. Wage // return wage public double get. Wage() { return wage; } // end method get. Wage // set hours worked 1992 -2007 Pearson Education, Inc. All rights reserved.
47 class – Hourly. Employee (cont) 30 // set hours worked 31 public void set. Hours( double hours. Worked ) 32 { 33 hours = ( ( hours. Worked >= 0. 0 ) && ( hours. Worked <= 168. 0 ) ) ? 34 hours. Worked : 0. 0; 35 } // end method set. Hours 36 37 // return hours worked 38 public double get. Hours() 39 { 40 return hours; 41 } // end method get. Hours 1992 -2007 Pearson Education, Inc. All rights reserved.
48 class – Hourly. Employee (cont) 43 44 45 // calculate earnings; override abstract method earnings in Employ public double earnings() { 46 47 48 49 50 if ( get. Hours() <= 40 ) // no overtime return get. Wage() * get. Hours(); else return 40 * get. Wage() + ( gethours() - 40 ) * get. Wage() * 1. } // end method earnings 51 52 // return String representation of Hourly. Employee object 53 54 public String to. String() { 55 56 57 58 59 return String. format( "hourly employee: %sn%s: $%, . 2 f; %s: %, super. to. String(), "hourly wage", get. Wage(), "hours worked", get. Hours() ); } // end method to. String } // end class Hourly. Employee 1992 -2007 Pearson Education, Inc. All rights reserved.
49 class - Commission. Employee • Extends class Employee – instanece variable gross. Sales and commission. Rate – should implement earnings method • returns gross. Sales times commission rate of the employee – A fife parameter constructor • calls super class constructor as the first statement • set the additional variables using set methods – to. String method overrides Employee’s to. String method • calls super’s to. String method using the keyword super 1992 -2007 Pearson Education, Inc. All rights reserved.
50 class - Commission. Employee 4 public class Commission. Employee extends Employee 5 { 6 protected double gross. Sales; // gross weekly sales 7 protected double commission. Rate; // commission percentage 8 9 // five-argument constructor 10 public Commission. Employee( String first, String last, String ssn, double sales, double rate ) 12 { 13 super( first, last, ssn ); 14 set. Gross. Sales( sales ); 15 set. Commission. Rate( rate ); 16 } // end five-argument Commission. Employee constructor 17 1992 -2007 Pearson Education, Inc. All rights reserved.
class – Commission. Employee (cont) 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 51 // set commission rate public void set. Commission. Rate( double rate ) { commission. Rate = ( rate > 0. 0 && rate < 1. 0 ) ? rate : 0. 0; } // end method set. Commission. Rate // return commission rate public double get. Commission. Rate() { return commission. Rate; } // end method get. Commission. Rate // set gross sales amount public void set. Gross. Sales( double sales ) { gross. Sales = ( sales < 0. 0 ) ? 0. 0 : sales; } // end method set. Gross. Sales // return gross sales amount public double get. Gross. Sales() { return gross. Sales; } // end method get. Gross. Sales 1992 -2007 Pearson Education, Inc. All rights reserved.
class – Commission. Employee (cont) 42 // calculate earnings; override abstract method earnings in Employee 43 public double earnings() 44 { 45 46 47 48 49 50 51 52 53 54 55 56 52 return get. Commission. Rate() * get. Gross. Sales(); } // end method earnings // return String representation of Commission. Employee object public String to. String() { return String. format( "%s: %sn%s: $%, . 2 f; %s: %. 2 f", "commission employee", super. to. String(), "gross sales", get. Gross. Sales(), "commission rate", get. Commission. Rate() ); } // end method to. String } // end class Commission. Employee 1992 -2007 Pearson Education, Inc. All rights reserved.
class Base. Plus. Commission. Employee 53 • Extends class Commission. Employee – instanece variable base. Salary – should implement earnings method • returns gross. Sales times commission rate of the employee – by calling super’s earning method • adding base. Salary – A six parameter constructor • calls super class constructor as the first statement • set the additional variable base. Salary using set methods – to. String method overrides Commssion. Employee’s to. String method • calls super’s to. String method using the keyword super 1992 -2007 Pearson Education, Inc. All rights reserved.
class Base. Plus. Commission. Employee 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 23 24 25 26 54 public class Base. Plus. Commission. Employee extends Commission. Employee { private double base. Salary; // base salary per week // six-argument constructor public Base. Plus. Commission. Employee( String first, String last, String ssn, double sales, double rate, double salary ) { super( first, last, ssn, sales, rate ); set. Base. Salary( salary ); // validate and store base salary } // end six-argument Base. Plus. Commission. Employee constructor // set base salary public void set. Base. Salary( double salary ) { base. Salary = ( salary < 0. 0 ) ? 0. 0 : salary; // non-negative } // end method set. Base. Salary // return base salary public double get. Base. Salary() { return base. Salary; } // end method get. Base. Salary 1992 -2007 Pearson Education, Inc. All rights reserved.
class – Base. Plus. Commission. Employee (cont) 55 27 28 // calculate earnings; override method earnings in Commission. Employee 29 public double earnings() 30 { 31 return get. Base. Salary() + super. earnings(); 32 } // end method earnings 33 34 // return String representation of Base. Plus. Commission. Employee object 35 public String to. String() 36 { 37 return String. format( "%s %s; %s: $%, . 2 f", 38 "base-salaried", super. to. String(), 39 "base salary", get. Base. Salary() ); 40 41 } // end method to. String } // end class Base. Plus. Commission. Employee 1992 -2007 Pearson Education, Inc. All rights reserved.
56 class - Payroll. System. Test • Creates four of the concrete emloyee types – Hourly, salaried, commission, base. Plus. Commission • Display using to. String and earning methods for each subclass • Declare and instantiate an 4 element array of Emloyee – super class – Employees a 4 element array of Emloyee • Assign each element of emloyees of type Emloyee a subclass object – emloyees[0] = salaried. Emloyee; – super class variable to subclass object 1992 -2007 Pearson Education, Inc. All rights reserved.
57 class - Payroll. System. Test • iterate over all emloyees using the emloyees array – Display their characteristics and earnings invoking – to. String and earnings methods on super class variables – if the type of the reference object is Base. Plus. Commission. Emloyee • increare its salary by 10% • Finally, print the class of each emloyee 1992 -2007 Pearson Education, Inc. All rights reserved.
58 class - Payroll. System. Test 4 5 6 7 public class Payroll. System. Test { public static void main( String args[] ) { 8 9 10 // create subclass objects Salaried. Employee salaried. Employee = new Salaried. Employee( "John", "Smith", "111 -11 -1111", 800. 00 ); 11 12 Hourly. Employee hourly. Employee = new Hourly. Employee( "Karen", "Price", "222 -22 -2222", 16. 75, 40 ); 13 14 15 16 17 18 Commission. Employee commission. Employee = new Commission. Employee( "Sue", "Jones", "333 -33 -3333", 10000, . 06 ); Base. Plus. Commission. Employee base. Plus. Commission. Employee = new Base. Plus. Commission. Employee( "Bob", "Lewis", "444 -44 -4444", 5000, . 04, 300 ); 1992 -2007 Pearson Education, Inc. All rights reserved.
59 class – Payroll. System. Test (cont) 19 20 System. out. println( "Employees processed individually: n" ); 22 System. out. printf( "%sn%s: $%, . 2 fnn", 23 salaried. Employee, "earned", salaried. Employee. earnings() ); 24 System. out. printf( "%sn%s: $%, . 2 fnn", 25 hourly. Employee, "earned", hourly. Employee. earnings() ); 26 System. out. printf( "%sn%s: $%, . 2 fnn", 27 commission. Employee, "earned", commission. Employee. earnings() ); 28 System. out. printf( "%sn%s: $%, . 2 fnn", 29 base. Plus. Commission. Employee, 30 "earned", base. Plus. Commission. Employee. earnings() ); 31 1992 -2007 Pearson Education, Inc. All rights reserved.
60 class – Payroll. System. Test (cont) 32 33 // create four-element Employee array Employee employees[] = new Employee[ 4 ]; 34 35 // initialize array with Employees 36 employees[ 0 ] = salaried. Employee; 37 employees[ 1 ] = hourly. Employee; 38 employees[ 2 ] = commission. Employee; 39 employees[ 3 ] = base. Plus. Commission. Employee; 41 System. out. println( "Employees processed polymorphically: n" ); 42 1992 -2007 Pearson Education, Inc. All rights reserved.
61 class – Payroll. System. Test (cont) 43 44 45 46 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 // generically process each element in array employees for ( Employee current. Employee : employees ) { System. out. println( current. Employee ); // invokes to. String // determine whether element is a Base. Plus. Commission. Employee if ( current. Employee instanceof Base. Plus. Commission. Employee ) { // downcast Employee reference to // Base. Plus. Commission. Employee reference Base. Plus. Commission. Employee employee = ( Base. Plus. Commission. Employee ) current. Employee; double old. Base. Salary = employee. get. Base. Salary(); employee. set. Base. Salary( 1. 10 * old. Base. Salary ); System. out. printf( "new base salary with 10%% increase is: $%, . 2 fn" , employee. get. Base. Salary() ); } // end if System. out. printf( "earned $%, . 2 fnn", current. Employee. earnings() ); } // end for 1992 -2007 Pearson Education, Inc. All rights reserved.
62 class – Payroll. System. Test (cont) 66 67 // get type name of each object in employees array 68 for ( int j = 0; j < employees. length; j++ ) 69 System. out. printf( "Employee %d is a %sn", j, 70 employees[ j ]. get. Class(). get. Name() ); 71 } // end main 72} // end class Payroll. System. Test 1992 -2007 Pearson Education, Inc. All rights reserved.
63 output Employees processed individually: salaried employee: John Smith social security number: 111 -11 -1111 weekly salary: $800. 00 earned: $800. 00 hourly employee: Karen Price social security number: 222 -22 -2222 hourly wage: $16. 75; hours worked: 40. 00 earned: $670. 00 commission employee: Sue Jones social security number: 333 -33 -3333 gross sales: $10, 000. 00; commission rate: 0. 06 earned: $600. 00 base-salaried commission employee: Bob Lewis social security number: 444 -44 -4444 gross sales: $5, 000. 00; commission rate: 0. 04; base salary: $300. 00 1992 -2007 Pearson Education, Inc. All rights reserved.
64 output (cont) Employees processed polymorphically: salaried employee: John Smith social security number: 111 -11 -1111 weekly salary: $800. 00 earned $800. 00 hourly social hourly earned employee: Karen Price security number: 222 -22 -2222 wage: $16. 75; hours worked: 40. 00 $670. 00 commission employee: Sue Jones social security number: 333 -33 -3333 gross sales: $10, 000. 00; commission rate: 0. 06 earned $600. 00 base-salaried commission employee: Bob Lewis social security number: 444 -44 -4444 gross sales: $5, 000. 00; commission rate: 0. 04; base salary: $300. 00 new base salary with 10% increase is: $330. 00 earned $530. 00 Employee 0 1 2 3 is is a a Salaried. Employee Hourly. Employee Commission. Employee Base. Plus. Commission. Employee 1992 -2007 Pearson Education, Inc. All rights reserved.
65 Array of Emloyee - emloyees Employees Each element of type Emloyee 0 1 2 3 Base. Plus. Commission. Emloyee object salaried. Emloyee Object Hourly. Emloyee objcet commission. Emloyee object 1992 -2007 Pearson Education, Inc. All rights reserved.
66 class – Payroll. System. Test (cont) double total = 0. 0; // generically process each element in array employees for ( Employee current. Employee : employees ) { System. out. println( current. Employee ); // invokes to. String System. out. printf("earned $%, . 2 fnn", current. Employee. earnings() total += current. Employee. earnings(); } // end for 1992 -2007 Pearson Education, Inc. All rights reserved.
67 class – Payroll. System. Test (cont) • iterate over employees array elements – With current. Emloyee variable – current. Emloyee refers to each element of emloyees array respectively – A supercalss variable refere to a sublclass object • • current. Emloyee to salaried. Emloyee current. Emloyee to hourly. Emloyee current. Emloyee to commission. Emloyee current. Emloyee to Base. Plus. Commission. Emloyee – to. String and earnings method on supercalss variable • current. Employee. to. String(), current. Employee. earnigs(); – Each time refered objects to. String method is invoked • salsried. Emloyee object’s to. String e. g. 1992 -2007 Pearson Education, Inc. All rights reserved.
68 output (cont) • Last for loop over emloyees – – – – employees[ j ]. get. Class(). get. Name() get. Class – a method of objcet Returns the class of an object here What emloyees[j] refers The return type is of Class in java. lang employees[ j ]. get. Class(). get. Name() Underline part returns a Class object get. Name – method of Class returns name of the class as a String • can be wtitten as two java statements: Class cls = employees[ j ]. get. Class(); cls. get. Name(); 1992 -2007 Pearson Education, Inc. All rights reserved.
69 downcasting • Iterate over all employees • If the emlpyee is a Base. Plus. Commission employee – increase its salary by 10% • Reference variable – current. Emloyee – superclass • To increase salary use – set. Base. Salary method – Can not be called over supercalss – Because it is a subclass only method • Downcast the supercalss reference to a subclass variable and then use the subclass only methods 1992 -2007 Pearson Education, Inc. All rights reserved.
70 down. Casting for ( Employee current. Employee : employees ) { System. out. println( current. Employee ); // invokes to. String // determine whether element is a Base. Plus. Commission. Employee if ( current. Employee instanceof Base. Plus. Commission. Employee ) { // downcast Employee reference to // Base. Plus. Commission. Employee reference Base. Plus. Commission. Employee employee = ( Base. Plus. Commission. Employee ) current. Employee; double old. Base. Salary = employee. get. Base. Salary(); employee. set. Base. Salary( 1. 10 * old. Base. Salary ); System. out. printf( "new base salary with 10%% increase is: $%, . 2 fn" , employee. get. Base. Salary() ); } // end if System. out. printf( "earned $%, . 2 fnn", current. Employee. earnings() ); } // end for 1992 -2007 Pearson Education, Inc. All rights reserved.
71 Downcasting for this example • Refer to if ( current. Employee instanceof Base. Plus. Commission. Employee ) { // downcast Employee reference to // Base. Plus. Commission. Employee reference Base. Plus. Commission. Employee employee = ( Base. Plus. Commission. Employee ) current. Employee; double old. Base. Salary = employee. get. Base. Salary(); employee. set. Base. Salary( 1. 10 * old. Base. Salary ); System. out. printf( "new base salary with 10%% increase is: $%, . 2 fn", employee. get. Base. Salary() ); } // end if 1992 -2007 Pearson Education, Inc. All rights reserved.
72 Downcasting for this example if ( current. Employee instanceof Base. Plus. Commission. Employee ) True if x instanceof y is a relation between x and y What x refers is a what y refers When current. Emloyee refers to a Base. Plus. Commission. Emloyee true otherwise false 1992 -2007 Pearson Education, Inc. All rights reserved.
73 Downcasting for this example Base. Plus. Commission. Employee employee = ( Base. Plus. Commission. Employee ) current. Employee; // downcasting A super class variable – current. Employee is cast to a subclass variable – Base. Plus. Commission. Emloyee İf what current. Emloyee refers is a Base. Plus. Commission. Emloyee You can call subclass only methods then emloyee. get. Base. Salary(); emloyee. set. Base. Salary(1. 1*old. Salary); 1992 -2007 Pearson Education, Inc. All rights reserved.
74 Downcasting for this example Base. Plus. Commission. Employee employee = ( Base. Plus. Commission. Employee ) current. Employee; Downcast current. Emloyee reference to a Base. Plus. Commission. Emloyee variable Create a Base. Plus. Commission. Emloyee variable called employee Assign downcasted variable to employee Call subclass only methods over emloyee 1992 -2007 Pearson Education, Inc. All rights reserved.
75 another version possible without creating the employee reference: double old. Base. Salary = ((Base. Plus. Commission. Employee ) current. Employee). get. Base. Salary(); What current. Employee is refering is downcasted to a Base. Plus. Commission. Employee type object so its get. Base. Salary method can be invoked then change salary like that ((Base. Plus. Commission. Employee ) current. Employee). set. Base. Salary(1. 1*old. Bas e. Salary); 1992 -2007 Pearson Education, Inc. All rights reserved.
76 Downcasting - general (subclass_Name) super. Class variable; // downcasting A super class variable is cast to a subclass variable – İf what superclass variable refers is a subclass variable You can call subclass only methods then 1992 -2007 Pearson Education, Inc. All rights reserved.
5. 5. 6 Demonstrating Polymorphic Processing, Operator instanceof and Downcasting 77 • Dynamic binding – Also known as late binding – Calls to overridden methods are resolved at execution time, based on the type of object referenced • instanceof operator – Determines whether an object is an instance of a certain type 1992 -2007 Pearson Education, Inc. All rights reserved.
78 Common Programming Error 5. 3 Assigning a superclass variable to a subclass variable (without an explicit cast) is a compilation error. 1992 -2007 Pearson Education, Inc. All rights reserved.
79 Software Engineering Observation 5. 5 If at execution time the reference of a subclass object has been assigned to a variable of one of its direct or indirect superclasses, it is acceptable to cast the reference stored in that superclass variable back to a reference of the subclass type. Before performing such a cast, use the instanceof operator to ensure that the object is indeed an object of an appropriate subclass type. 1992 -2007 Pearson Education, Inc. All rights reserved.
80 Common Programming Error 5. 4 When downcasting an object, a Class. Cast. Exception occurs, if at execution time the object does not have an is-a relationship with the type specified in the cast operator. An object can be cast only to its own type or to the type of one of its superclasses. 1992 -2007 Pearson Education, Inc. All rights reserved.
5. 5. 6 Demonstrating Polymorphic Processing, Operator instanceof and Downcasting (Cont. ) 81 • Downcasting – Convert a reference to a superclass to a reference to a subclass – Allowed only if the object has an is-a relationship with the subclass • get. Class method – Inherited from Object – Returns an object of type Class • get. Name method of class Class – Returns the class’s name 1992 -2007 Pearson Education, Inc. All rights reserved.
5. 5. 7 Summary of the Allowed Assignments Between Superclass and Subclass Variables 82 • Superclass and subclass assignment rules – Assigning a superclass reference to a superclass variable is straightforward – Assigning a subclass reference to a subclass variable is straightforward – Assigning a subclass reference to a superclass variable is safe because of the is-a relationship • Referring to subclass-only members through superclass variables is a compilation error – Assigning a superclass reference to a subclass variable is a compilation error • Downcasting can get around this error 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 83 Declare abstract class Employee Attributes common to all employees Employee. java (1 of 3) 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 84 Employee. java (2 of 3) 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 85 Employee. java (3 of 3) abstract method earnings has no implementation 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 86 Class Salaried. Employee extends class Employee Salaried. Employee. java Call superclass constructor (1 of 2) Call set. Weekly. Salary method Validate and set weekly salary value 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 87 Salaried. Employee. java Override earnings method so Salaried. Employee can be concrete (2 of 2) Override to. String method Call superclass’s version of to. String 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 88 Class Hourly. Employee extends class Employee Hourly. Employee. java Call superclass constructor (1 of 2) Validate and set hourly wage value 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 89 Hourly. Employee Validate and set hours worked value . java (2 of 2) Override earnings method so Hourly. Employee can be concrete Override to. String method Call superclass’s to. String method 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 90 Class Commission. Employee extends class Employee Commission. Employee. java (1 of 3) Call superclass constructor Validate and set commission rate value 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 91 Commission. Employee. java (2 of 3) Validate and set the gross sales value 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 92 Override earnings method so Commission. Employee can be concrete Commission. Employee. java Override to. String method (3 of 3) Call superclass’s to. String method 1992 -2007 Pearson Education, Inc. All rights reserved.
Class Base. Plus. Commission. Employee extends class Commission. Employee Outline 93 Base. Plus. Commission Employee. java Call superclass constructor (1 of 2) Validate and set base salary value 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 94 Base. Plus. Commission Employee. java Override earnings method Call superclass’s earnings method (2 of 2) Override to. String method Call superclass’s to. String method 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 95 Payroll. System. Test. java (1 of 5) 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 96 Payroll. System. Test. java (2 of 5) Assigning subclass objects to supercalss variables Implicitly and polymorphically call to. String 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 97 If the current. Employee variable points to a Base. Plus. Commission. Employee object Payroll. System. Test Downcast current. Employee to a. java Base. Plus. Commission. Employee reference (3 of 5) Give Base. Plus. Commission. Employees a 10% base salary bonus Polymorphically call earnings method Call get. Class and get. Name methods to display each Employee subclass object’s class name 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 98 Payroll. System. Test. java (4 of 5) 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 99 Same results as when the employees were processed individually Payroll. System. Test. java (5 of 5) Base salary is increased by 10% Each employee’s type is displayed 1992 -2007 Pearson Education, Inc. All rights reserved.
100 5. 6 final Methods and Classes • final methods – Cannot be overridden in a subclass – private and static methods are implicitly final – final methods are resolved at compile time, this is known as static binding • Compilers can optimize by inlining the code • final classes – Cannot be extended by a subclass – All methods in a final class are implicitly final 1992 -2007 Pearson Education, Inc. All rights reserved.
101 Software Engineering Observation 5. 6 In the Java API, the vast majority of classes are not declared final. This enables inheritance and polymorphism—the fundamental capabilities of object-oriented programming. However, in some cases, it is important to declare classes final—typically for security reasons. 1992 -2007 Pearson Education, Inc. All rights reserved.
5. 7 Case Study: Creating and Using Interfaces 102 • Interfaces – Keyword interface – Contains only constants and abstract methods • All fields are implicitly public, static and final • All methods are implicitly public abstract methods – Classes can implement interfaces • The class must declare each method in the interface using the same signature or the class must be declared abstract – Typically used when disparate classes need to share common methods and constants – Normally declared in their own files with the same names as the interfaces and with the. java file-name extension 1992 -2007 Pearson Education, Inc. All rights reserved.
103 Good Programming Practice 5. 1 According to Chapter 9 of the Java Language Specification, it is proper style to declare an interface’s methods without keywords public and abstract because they are redundant in interface method declarations. Similarly, constants should be declared without keywords public, static and final because they, too, are redundant. 1992 -2007 Pearson Education, Inc. All rights reserved.
104 Common Programming Error 5. 6 Failing to implement any method of an interface in a concrete class that implements the interface results in a syntax error indicating that the class must be declared abstract. 1992 -2007 Pearson Education, Inc. All rights reserved.
105 5. 7. 1 Developing a Payable Hierarchy • Payable interface – Contains method get. Payment. Amount – Is implemented by the Invoice and Employee classes • UML representation of interfaces – Interfaces are distinguished from classes by placing the word “interface” in guillemets ( « and » ) above the interface name – The relationship between a class and an interface is known as realization • A class “realizes” the methods of an interface 1992 -2007 Pearson Education, Inc. All rights reserved.
106 Fig. 10 | Payable interface hierarchy UML class diagram. 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 107 Payable. java Declare interface Payable Declare get. Payment. Amount method which is implicitly public and abstract 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 108 Class Invoice implements interface Payable Invoice. java (1 of 3) 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 109 Invoice. java (1 of 3) 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 110 Invoice. java (2 of 3) 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 111 Invoice. java (3 of 3) Declare get. Payment. Amount to fulfill contract with interface Payable 1992 -2007 Pearson Education, Inc. All rights reserved.
112 5. 7. 3 Creating Class Invoice • A class can implement as many interfaces as it needs – Use a comma-separated list of interface names after keyword implements • Example: public class Class. Name extends Superclass. Name implements First. Interface, Second. Interface, … 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline Class Employee implements interface Payable 113 Employee. java (1 of 3) 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 114 Employee. java (2 of 3) 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 115 Employee. java (3 of 3) get. Payment. Amount method is not implemented here 1992 -2007 Pearson Education, Inc. All rights reserved.
5. 7. 5 Modifying Class Salaried. Employee for Use in the Payable Hierarchy 116 • Objects of any subclasses of the class that implements the interface can also be thought of as objects of the interface – A reference to a subclass object can be assigned to an interface variable if the superclass implements that interface 1992 -2007 Pearson Education, Inc. All rights reserved.
117 Software Engineering Observation 5. 7 Inheritance and interfaces are similar in their implementation of the “is-a” relationship. An object of a class that implements an interface may be thought of as an object of that interface type. An object of any subclasses of a class that implements an interface also can be thought of as an object of the interface type. 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 118 Class Salaried. Employee extends class Employee (which implements interface Payable) Salaried. Employee. java (1 of 2) 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 119 Salaried. Employee. java (2 of 2) Declare get. Payment. Amount method instead of earnings method 1992 -2007 Pearson Education, Inc. All rights reserved.
120 Software Engineering Observation 5. 8 The “is-a” relationship that exists between superclasses and subclasses, and between interfaces and the classes that implement them, holds when passing an object to a method. When a method parameter receives a variable of a superclass or interface type, the method processes the object received as an argument polymorphically. 1992 -2007 Pearson Education, Inc. All rights reserved.
121 Software Engineering Observation 5. 9 Using a superclass reference, we can polymorphically invoke any method specified in the superclass declaration (and in class Object). Using an interface reference, we can polymorphically invoke any method specified in the interface declaration (and in class Object). 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 122 Declare array of Payable variables Payable. Interface Test. java Assigning references to (1 of 2) objects to Invoice Payable variables Assigning references to Salaried. Employee objects to Payable variables 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline Call to. String and get. Payment. Amount methods polymorphically 123 Payable. Interface Test. java (2 of 2) 1992 -2007 Pearson Education, Inc. All rights reserved.
Outline 124 Payable. Interface Test. java (2 of 2) 1992 -2007 Pearson Education, Inc. All rights reserved.
125 Software Engineering Observation 5. 10 All methods of class Object can be called by using a reference of an interface type. A reference refers to an object, and all objects inherit the methods of class Object. 1992 -2007 Pearson Education, Inc. All rights reserved.
126 5. 7. 7 Declaring Constants with Interfaces • Interfaces can be used to declare constants used in many class declarations – These constants are implicitly public, static and final – Using a static import declaration allows clients to use these constants with just their names 1992 -2007 Pearson Education, Inc. All rights reserved.
127 Software Engineering Observation 5. 11 It is considered a better programming practice to create sets of constants as enumerations with keyword enum. See Section 6. 10 for an introduction to enum and Section 8. 9 for additional enum details. 1992 -2007 Pearson Education, Inc. All rights reserved.
128 Fig. 10. 16 | Common interfaces of the Java API. (Part 1 of 2) 1992 -2007 Pearson Education, Inc. All rights reserved.
129 Fig. 10. 16 | Common interfaces of the Java API. (Part 2 of 2) 1992 -2007 Pearson Education, Inc. All rights reserved.
130 Fig. 10. 17 | My. Shape hierarchy. 1992 -2007 Pearson Education, Inc. All rights reserved.
131 Fig. 10. 18 | My. Shape hierarchy with My. Bounded. Shape . 1992 -2007 Pearson Education, Inc. All rights reserved.
132 Fig. 10. 19 | Attributes and operations of classes Balance. Inquiry, Withdrawal and Deposit. 1992 -2007 Pearson Education, Inc. All rights reserved.
133 5. 8 Java SE 8 Interfaces • This section introduces interface features that were added in • Java SE • We discuss these in more detail in later chapters. 1992 -2007 Pearson Education, Inc. All rights reserved.
134 default interface methods • Prior to Java SE 8, interface methods could be only public abstract methods. – An interface specified what operations an implementing class must perform but not how the class should perform them. • In Java SE 8, interfaces also may contain public default methods with concrete default implementations that specify how operations are performed when an implementing class does not override the methods. • If a class implements such an interface, the class also receives the interface’s default implementations (if any). • To declare a default method, place the keyword default before the method’s return type and provide a concrete method implementation. 1992 -2007 Pearson Education, Inc. All rights reserved.
135 Adding Methods to Existing Interfaces • Any class that implements the original interface will not break when a default method is added. – The class simply receives the new default method. • When a class implements a Java SE 8 interface, the class “signs a contract” with the compiler that says, – “I will declare all the abstract methods specified by the interface or I will declare my class abstract” • The implementing class is not required to override the interface’s default methods, but it can if necessary. 1992 -2007 Pearson Education, Inc. All rights reserved.
136 Interfaces vs. abstract Classes • Prior to Java SE 8, an interface was typically used (rather than an abstract class) when there were no implementation details to inherit—no fields and no method implementations. • With default methods, you can instead declare common method implementations in interfaces • This gives you more flexibility in designing your classes, because a class can implement many interfaces, but can extend only one superclass 1992 -2007 Pearson Education, Inc. All rights reserved.
137 static interface methods • Prior to Java SE 8, it was common to associate with an interface a class containing static helper methods for working with objects that implemented the interface. • In Chapter 16, you’ll learn about class Collections which contains many static helper methods for working with objects that implement interfaces Collection, List, Set and more. • Collections method sort can sort objects of any class that implements interface List. • With static interface methods, such helper methods can now be declared directly in interfaces rather than in separate classes. 1992 -2007 Pearson Education, Inc. All rights reserved.
138 public interface My. IF { // This is a "normal" interface method declaration. // It does NOT define a default implementation. int get. Number(); // This is a default method. Notice that it provides // a default implementation. default String get. String() { return "Default String"; } } 1992 -2007 Pearson Education, Inc. All rights reserved.
139 // Implement My. IF. class My. IFImp implements My. IF { // Only get. Number() defined by My. IF needs to be implemented. // get. String() can be allowed to default. public int get. Number() { return 100; } } 1992 -2007 Pearson Education, Inc. All rights reserved.
140 // Use the default method. class Default. Method. Demo { public static void main(String args[]) { My. IFImp obj = new My. IFImp(); // Can call get. Number(), because it is explicitly // implemented by My. IFImp: System. out. println(obj. get. Number()); // Can also call get. String(), because of default // implementation: System. out. println(obj. get. String()); } } 1992 -2007 Pearson Education, Inc. All rights reserved.
141 Output 100 Default String 1992 -2007 Pearson Education, Inc. All rights reserved.
142 class My. IFImp 2 implements My. IF { // Here, implementations for both // get. Number( ) and get. String( ) are provided. public int get. Number() { return 100; } public String get. String() { return "This is a different string. "; } } 1992 -2007 Pearson Education, Inc. All rights reserved.
143 public interface My. IF { // This is a "normal" interface method declaration. // It does NOT define a default implementation. int get. Number(); // This is a default method. Notice that it provides // a default implementation. default String get. String() { return "Default String"; } // This is a static interface method. static int get. Default. Number() { return 0; } } 1992 -2007 Pearson Education, Inc. All rights reserved.
144 • The get. Default. Number( ) method can be called, as shown here: int def. Num = My. IF. get. Default. Number(); 1992 -2007 Pearson Education, Inc. All rights reserved.
145 Example • My. Array class implements two interfaces • Sort. IF: containing static sert methods – selection. Sort, buble. Sort • Search. IF: containing static search methods – linear. Search, binary. Serch • All these methods takes an array (int type) and etither sort or search a key in the array 1992 -2007 Pearson Education, Inc. All rights reserved.
- Slides: 145