- 10.1 Introduction
- 10.2 Polymorphism Examples
- 10.3 Demonstrating Polymorphic Behavior
- 10.4 Abstract Classes and Methods
- 10.5 Case Study: Payroll System Using Polymorphism
- 10.6 final Methods and Classes
- 10.7 Case Study: Creating and Using Interfaces
- 10.8 (Optional) Software Engineering Case Study: Incorporating Inheritance into the ATM System
- 10.9 Wrap-Up
10.7 Case Study: Creating and Using Interfaces
Our next example (Figs. 10.11–10.13) reexamines the payroll system of Section 10.5. Suppose that the company involved wishes to perform several accounting operations in a single accounts payable application—in addition to calculating the earnings that must be paid to each employee, the company must also calculate the payment due on each of several invoices (i.e., bills for goods purchased). Though applied to unrelated things (i.e., employees and invoices), both operations have to do with obtaining some kind of payment amount. For an employee, the payment refers to the employee’s earnings. For an invoice, the payment refers to the total cost of the goods listed on the invoice. Can we calculate such different things as the payments due for employees and invoices in a single application polymorphically? Does Java offer a capability that requires that unrelated classes implement a set of common methods (e.g., a method that calculates a payment amount)? Java interfaces offer exactly this capability.
Interfaces define and standardize the ways in which things such as people and systems can interact with one another. For example, the controls on a radio serve as an interface between radio users and a radio’s internal components. The controls allow users to perform only a limited set of operations (e.g., changing the station, adjusting the volume, choosing between AM and FM), and different radios may implement the controls in different ways (e.g., using push buttons, dials, voice commands). The interface specifies what operations a radio must permit users to perform but does not specify how the operations are performed. Similarly, the interface between a driver and a car with a manual transmission includes the steering wheel, the gear shift, the clutch pedal, the gas pedal and the brake pedal. This same interface is found in nearly all manual transmission cars, enabling someone who knows how to drive one particular manual transmission car to drive just about any manual transmission car. The components of each individual car may look different, but their general purpose is the same—to allow people to drive the car.
Software objects also communicate via interfaces. A Java interface describes a set of methods that can be called on an object, to tell the object to perform some task or return some piece of information, for example. The next example introduces an interface named Payable to describe the functionality of any object that must be capable of being paid and thus must offer a method to determine the proper payment amount due. An interface declaration begins with the keyword interface and contains only constants and abstract methods. Unlike classes, all interface members must be public, and interfaces may not specify any implementation details, such as concrete method declarations and instance variables. So all methods declared in an interface are implicitly public abstract methods and all fields are implicitly public, static and final.
To use an interface, a concrete class must specify that it implements the interface and must declare each method in the interface with the signature specified in the interface declaration. A class that does not implement all the methods of the interface is an abstract class and must be declared abstract. Implementing an interface is like signing a contract with the compiler that states, “I will declare all the methods specified by the interface or I will declare my class abstract.”
An interface is typically used when disparate (i.e., unrelated) classes need to share common methods and constants. This allows objects of unrelated classes to be processed polymorphically—objects of classes that implement the same interface can respond to the same method calls. You can create an interface that describes the desired functionality, then implement this interface in any classes that require that functionality. For example, in the accounts payable application developed in this section, we implement interface Payable in any class that must be able to calculate a payment amount (e.g., Employee, Invoice).
An interface is often used in place of an abstract class when there is no default implementation to inherit—that is, no fields and no default method implementations. Interfaces are typically public types, so they are normally declared in files by themselves with the same name as the interface and the .java file-name extension.
10.7.1 Developing a Payable Hierarchy
To build an application that can determine payments for employees and invoices alike, we first create interface Payable, which contains method getPaymentAmount that returns a double amount that must be paid for an object of any class that implements the interface. Method getPaymentAmount is a general purpose version of method earnings of the Employee hierarchy—method earnings calculates a payment amount specifically for an Employee, while getPaymentAmount can be applied to a broad range of unrelated objects. After declaring interface Payable, we introduce class Invoice, which implements interface Payable. We then modify class Employee such that it also implements interface Payable. Finally, we update Employee subclass SalariedEmployee to “fit” into the Payable hierarchy (i.e., we rename SalariedEmployee method earnings as getPaymentAmount).
Classes Invoice and Employee both represent things for which the company must be able to calculate a payment amount. Both classes implement Payable, so a program can invoke method getPaymentAmount on Invoice objects and Employee objects alike. As we’ll soon see, this enables the polymorphic processing of Invoices and Employees required for our company’s accounts payable application.
The UML class diagram in Fig. 10.10 shows the hierarchy used in our accounts payable application. The hierarchy begins with interface Payable. The UML distinguishes an interface from other classes by placing the word “interface” in guillemets (« and ») above the interface name. The UML expresses the relationship between a class and an interface through a relationship known as a realization. A class is said to “realize,” or implement, the methods of an interface. A class diagram models a realization as a dashed arrow with a hollow arrowhead pointing from the implementing class to the interface. The diagram in Fig. 10.10 indicates that classes Invoice and Employee each realize (i.e., implement) interface Payable. Note that, as in the class diagram of Fig. 10.2, class Employee appears in italics, indicating that it is an abstract class. Concrete class SalariedEmployee extends Employee and inherits its superclass’s realization relationship with interface Payable.
Fig. 10.10 Payable interface hierarchy UML class diagram.
10.7.2 Declaring Interface Payable
The declaration of interface Payable begins in Fig. 10.11 at line 4. Interface Payable contains public abstract method getPaymentAmount (line 6). Note that the method is not explicitly declared public or abstract. Interface methods must be public and abstract, so they do not need to be declared as such. Interface Payable has only one method—interfaces can have any number of methods. (We’ll see later in the book the notion of “tagging interfaces”—these actually have no methods. In fact, a tagging interface contains no constant values, either—it simply contains an empty interface declaration.) In addition, method getPaymentAmount has no parameters, but interface methods can have parameters.
Fig. 10.11. Payable interface declaration.
1 // Fig. 10.11: Payable.java 2 // Payable interface declaration. 3 4 public interface Payable 5 { 6 double getPaymentAmount(); // calculate payment; no implementation 7 } // end interface Payable
10.7.3 Creating Class Invoice
We now create class Invoice (Fig. 10.12) to represent a simple invoice that contains billing information for only one kind of part. The class declares private instance variables partNumber, partDescription, quantity and pricePerItem (in lines 6–9) that indicate the part number, a description of the part, the quantity of the part ordered and the price per item. Class Invoice also contains a constructor (lines 12–19), get and set methods (lines 22–67) that manipulate the class’s instance variables and a toString method (lines 70–75) that returns a string representation of an Invoice object. Note that methods setQuantity (lines 46–49) and setPricePerItem (lines 58–61) ensure that quantity and pricePerItem obtain only nonnegative values.
Fig. 10.12. Invoice class that implements Payable.
1 // Fig. 10.12: Invoice.java 2 // Invoice class implements Payable. 3 4 public class Invoice implements Payable 5 { 6 private String partNumber; 7 private String partDescription; 8 private int quantity; 9 private double pricePerItem; 10 11 // four-argument constructor 12 public Invoice( String part, String description, int count, 13 double price ) 14 { 15 partNumber = part; 16 partDescription = description; 17 setQuantity( count ); // validate and store quantity 18 setPricePerItem( price ); // validate and store price per item 19 } // end four-argument Invoice constructor 20 21 // set part number 22 public void setPartNumber( String part ) 23 { 24 partNumber = part; 25 } // end method setPartNumber 26 27 // get part number 28 public String getPartNumber() 29 { 30 return partNumber; 31 } // end method getPartNumber 32 33 // set description 34 public void setPartDescription( String description ) 35 { 36 partDescription = description; 37 } // end method setPartDescription 38 39 // get description 40 public String getPartDescription() 41 { 42 return partDescription; 43 } // end method getPartDescription 44 45 // set quantity 46 public void setQuantity( int count ) 47 { 48 quantity = ( count < 0 ) ? 0 : count; // quantity cannot be negative 49 } // end method setQuantity 50 51 // get quantity 52 public int getQuantity() 53 { 54 return quantity; 55 } // end method getQuantity 56 57 // set price per item 58 public void setPricePerItem( double price ) 59 { 60 pricePerItem = ( price < 0.0 ) ? 0.0 : price; // validate price 61 } // end method setPricePerItem 62 63 // get price per item 64 public double getPricePerItem() 65 { 66 return pricePerItem; 67 } // end method getPricePerItem 68 69 // return String representation of Invoice object 70 public String toString() 71 { 72 return String.format( "%s: \n%s: %s (%s) \n%s: %d \n%s: $%,.2f", 73 "invoice", "part number", getPartNumber(), getPartDescription(), 74 "quantity", getQuantity(), "price per item", getPricePerItem() ); 75 } // end method toString 76 77 // method required to carry out contract with interface Payable 78 public double getPaymentAmount() 79 { 80 return getQuantity() * getPricePerItem(); // calculate total cost 81 } // end method getPaymentAmount 82 } // end class Invoice
Line 4 of Fig. 10.12 indicates that class Invoice implements interface Payable. Like all classes, class Invoice also implicitly extends Object. Java does not allow subclasses to inherit from more than one superclass, but it does allow a class to inherit from a superclass and implement more than one interface. In fact, a class can implement as many interfaces as it needs, in addition to extending one other class. To implement more than one interface, use a comma-separated list of interface names after keyword implements in the class declaration, as in:
public class ClassName extends SuperclassName implements FirstInterface, SecondInterface, ...
All objects of a class that implement multiple interfaces have the is-a relationship with each implemented interface type.
Class Invoice implements the one method in interface Payable. Method getPaymentAmount is declared in lines 78–81. The method calculates the total payment required to pay the invoice. The method multiplies the values of quantity and pricePerItem (obtained through the appropriate get methods) and returns the result (line 80). This method satisfies the implementation requirement for this method in interface Payable—we have fulfilled the interface contract with the compiler.
10.7.4 Modifying Class Employee to Implement Interface Payable
We now modify class Employee such that it implements interface Payable. Figure 10.13 contains the modified Employee class. This class declaration is identical to that of Fig. 10.4 with only two exceptions. First, line 4 of Fig. 10.13 indicates that class Employee now implements interface Payable. Second, since Employee now implements interface Payable, we must rename earnings to getPaymentAmount throughout the Employee hierarchy. As with method earnings in the version of class Employee in Fig. 10.4, however, it does not make sense to implement method getPaymentAmount in class Employee because we cannot calculate the earnings payment owed to a general Employee—first we must know the specific type of Employee. In Fig. 10.4, we declared method earnings as abstract for this reason, and as a result class Employee had to be declared abstract. This forced each Employee subclass to override earnings with a concrete implementation.
Fig. 10.13. Employee class that implements Payable.
1 // Fig. 10.13: Employee.java 2 // Employee abstract superclass implements Payable. 3 4 public abstract class Employee implements Payable 5 { 6 private String firstName; 7 private String lastName; 8 private String socialSecurityNumber; 9 10 // three-argument constructor 11 public Employee( String first, String last, String ssn ) 12 { 13 firstName = first; 14 lastName = last; 15 socialSecurityNumber = ssn; 16 } // end three-argument Employee constructor 17 18 // set first name 19 public void setFirstName( String first ) 20 { 21 firstName = first; 22 } // end method setFirstName 23 24 // return first name 25 public String getFirstName() 26 { 27 return firstName; 28 } // end method getFirstName 29 30 // set last name 31 public void setLastName( String last ) 32 { 33 lastName = last; 34 } // end method setLastName 35 36 // return last name 37 public String getLastName() 38 { 39 return lastName; 40 } // end method getLastName 41 42 // set social security number 43 public void setSocialSecurityNumber( String ssn ) 44 { 45 socialSecurityNumber = ssn; // should validate 46 } // end method setSocialSecurityNumber 47 48 // return social security number 49 public String getSocialSecurityNumber() 50 { 51 return socialSecurityNumber; 52 } // end method getSocialSecurityNumber 53 54 // return String representation of Employee object 55 public String toString() 56 { 57 return String.format( "%s %s\nsocial security number: %s", 58 getFirstName(), getLastName(), getSocialSecurityNumber() ); 59 } // end method toString 60 61 // Note: We do not implement Payable method getPaymentAmount here so 62 // this class must be declared abstract to avoid a compilation error. 63 } // end abstract class Employee
In Fig. 10.13, we handle this situation differently. Recall that when a class implements an interface, the class makes a contract with the compiler stating either that the class will implement each of the methods in the interface or that the class will be declared abstract. If the latter option is chosen, we do not need to declare the interface methods as abstract in the abstract class—they are already implicitly declared as such in the interface. Any concrete subclass of the abstract class must implement the interface methods to fulfill the superclass’s contract with the compiler. If the subclass does not do so, it too must be declared abstract. As indicated by the comments in lines 61–62, class Employee of Fig. 10.13 does not implement method getPaymentAmount, so the class is declared abstract. Each direct Employee subclass inherits the superclass’s contract to implement method getPaymentAmount and thus must implement this method to become a concrete class for which objects can be instantiated. A class that extends one of Employee’s concrete subclasses will inherit an implementation of getPaymentAmount and thus will also be a concrete class.
10.7.5 Modifying Class SalariedEmployee for Use in the Payable Hierarchy
Figure 10.14 contains a modified version of class SalariedEmployee that extends Employee and fulfills superclass Employee’s contract to implement method getPaymentAmount of interface Payable. This version of SalariedEmployee is identical to that of Fig. 10.5 with the exception that the version here implements method getPaymentAmount (lines 30–33) instead of method earnings. The two methods contain the same functionality but have different names. Recall that the Payable version of the method has a more general name to be applicable to possibly disparate classes. The remaining Employee subclasses (e.g., HourlyEmployee, CommissionEmployee and BasePlusCommissionEmployee) also must be modified to contain method getPaymentAmount in place of earnings to reflect the fact that Employee now implements Payable. We leave these modifications as an exercise and use only SalariedEmployee in our test program in this section.
Fig. 10.14. SalariedEmployee class that implements interface Payable method getPaymentAmount.
1 // Fig. 10.14: SalariedEmployee.java 2 // SalariedEmployee class extends Employee, which implements Payable. 3 4 public class SalariedEmployee extends Employee 5 { 6 private double weeklySalary; 7 8 // four-argument constructor 9 public SalariedEmployee( String first, String last, String ssn, 10 double salary ) 11 { 12 super( first, last, ssn ); // pass to Employee constructor 13 setWeeklySalary( salary ); // validate and store salary 14 } // end four-argument SalariedEmployee constructor 15 16 // set salary 17 public void setWeeklySalary( double salary ) 18 { 19 weeklySalary = salary < 0.0 ? 0.0 : salary; 20 } // end method setWeeklySalary 21 22 // return salary 23 public double getWeeklySalary() 24 { 25 return weeklySalary; 26 } // end method getWeeklySalary 27 28 // calculate earnings; implement interface Payable method that was 29 // abstract in superclass Employee 30 public double getPaymentAmount() 31 { 32 return getWeeklySalary(); 33 } // end method getPaymentAmount 34 35 // return String representation of SalariedEmployee object 36 public String toString() 37 { 38 return String.format( "salaried employee: %s\n%s: $%,.2f", 39 super.toString(), "weekly salary", getWeeklySalary() ); 40 } // end method toString 41 } // end class SalariedEmployee
When a class implements an interface, the same is-a relationship provided by inheritance applies. For example, class Employee implements Payable, so we can say that an Employee is a Payable. In fact, objects of any classes that extend Employee are also Payable objects. SalariedEmployee objects, for instance, are Payable objects. As with inheritance relationships, an object of a class that implements an interface may be thought of as an object of the interface type. Objects of any subclasses of the class that implements the interface can also be thought of as objects of the interface type. Thus, just as we can assign the reference of a SalariedEmployee object to a superclass Employee variable, we can assign the reference of a SalariedEmployee object to an interface Payable variable. Invoice implements Payable, so an Invoice object also is a Payable object, and we can assign the reference of an Invoice object to a Payable variable.
10.7.6 Using Interface Payable to Process Invoices and Employees Polymorphically
PayableInterfaceTest (Fig. 10.15) illustrates that interface Payable can be used to process a set of Invoices and Employees polymorphically in a single application. Line 9 declares payableObjects and assigns it an array of four Payable variables. Lines 12–13 assign the references of Invoice objects to the first two elements of payableObjects. Lines 14–17 then assign the references of SalariedEmployee objects to the remaining two elements of payableObjects. These assignments are allowed because an Invoice is a Payable, a SalariedEmployee is an Employee and an Employee is a Payable. Lines 23–29 use the enhanced for statement to polymorphically process each Payable object in payableObjects, printing the object as a String, along with the payment amount due. Note that line 27 invokes method toString off a Payable interface reference, even though toString is not declared in interface Payable—all references (including those of interface types) refer to objects that extend Object and therefore have a toString method. (Note that toString also can be invoked implicitly here.) Line 28 invokes Payable method getPaymentAmount to obtain the payment amount for each object in payableObjects, regardless of the actual type of the object. The output reveals that the method calls in lines 27– 28 invoke the appropriate class’s implementation of methods toString and getPaymentAmount. For instance, when currentEmployee refers to an Invoice during the first iteration of the for loop, class Invoice’s toString and getPaymentAmount execute.
Fig. 10.15. Payable interface test program processing Invoices and Employees polymorphically.
1 // Fig. 10.15: PayableInterfaceTest.java 2 // Tests interface Payable. 3 4 public class PayableInterfaceTest 5 { 6 public static void main( String args[] ) 7 { 8 // create four-element Payable array 9 Payable payableObjects[] = new Payable[ 4 ]; 10 11 // populate array with objects that implement Payable 12 payableObjects[ 0 ] = new Invoice( "01234", "seat", 2, 375.00 ); 13 payableObjects[ 1 ] = new Invoice( "56789", "tire", 4, 79.95 ); 14 payableObjects[ 2 ] = 15 new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00 ); 16 payableObjects[ 3 ] = 17 new SalariedEmployee( "Lisa", "Barnes", "888-88-8888", 1200.00 ); 18 19 System.out.println( 20 "Invoices and Employees processed polymorphically:\n" ); 21 22 // generically process each element in array payableObjects 23 for ( Payable currentPayable : payableObjects ) 24 { 25 // output currentPayable and its appropriate payment amount 26 System.out.printf( "%s \n%s: $%,.2f\n\n", 27 currentPayable.toString(), 28 "payment due", currentPayable.getPaymentAmount() ); 29 } // end for 30 } // end main 31 } // end class PayableInterfaceTest
Invoices and Employees processed polymorphically: invoice: part number: 01234 (seat) quantity: 2 price per item: $375.00 payment due: $750.00 invoice: part number: 56789 (tire) quantity: 4 price per item: $79.95 payment due: $319.80 salaried employee: John Smith social security number: 111-11-1111 weekly salary: $800.00 payment due: $800.00 salaried employee: Lisa Barnes social security number: 888-88-8888 weekly salary: $1,200.00 payment due: $1,200.00
10.7.7 Declaring Constants with Interfaces
As we mentioned an interface can declare constants. The constants are implicitly public, static and final—again, these keywords are not required in the interface declaration. One popular use of an interface is to declare a set of constants that can be used in many class declarations. Consider interface Constants:
public interface Constants { int ONE = 1; int TWO = 2; int THREE = 3; }
A class can use these constants by importing the interface, then referring to each constant as Constants.ONE, Constants.TWO and Constants.THREE. Note that a class can refer to the imported constants with just their names (i.e., ONE, TWO and THREE) if it uses a static import declaration (presented in Section 8.12) to import the interface.
10.7.8 Common Interfaces of the Java API
In this section, we overview several common interfaces found in the Java API. The power and flexibility of interfaces is used frequently throughout the Java API. These interfaces are implemented and used in the same manner as the interfaces you create (e.g., interface Payable in Section 10.7.2). As you’ll see throughout this book, the Java API’s interfaces enable you to use your own classes within the frameworks provided by Java, such as comparing objects of your own types and creating tasks that can execute concurrently with other tasks in the same program. Figure 10.16 presents a brief overview of a few of the more popular interfaces of the Java API.
Fig. 10.16. Common interfaces of the Java API.
Interface |
Description |
Comparable |
As you learned in Chapter 2, Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a class that implements the interface to be compared to one another. The interface contains one method, compareTo, that compares the object that calls the method to the object passed as an argument to the method. Classes must implement compareTo such that it returns a value indicating whether the object on which it is invoked is less than (negative integer return value), equal to (0 return value) or greater than (positive integer return value) the object passed as an argument, using any criteria specified by the programmer. For example, if class Employee implements Comparable, its compareTo method could compare Employee objects by their earnings amounts. Interface Comparable is commonly used for ordering objects in a collection such as an array. We use Comparable in Chapter 15, Generics, and Chapter 16, Collections. |
Serializable |
An interface used to identify classes whose objects can be written to (i.e., serialized) or read from (i.e., deserialized) some type of storage (e.g., file on disk, database field) or transmitted across a network. We use Serializable in Chapter 14, Files and Streams, and Chapter 19, Networking. |
Runnable |
Implemented by any class for which objects of that class should be able to execute in parallel using a technique called multithreading (discussed in Chapter 18, Multithreading). The interface contains one method, run, which describes the behavior of an object when executed. |
GUI event-listener interfaces |
You work with graphical user interfaces (GUIs) every day. For example, in your web browser, you might type in a text field the address of a website to visit, or you might click a button to return to the previous site you visited. When you type a website address or click a button in the web browser, the browser must respond to your interaction and perform the desired task for you. Your interaction is known as an event, and the code that the browser uses to respond to an event is known as an event handler. In Chapter 11, GUI Components: Part 1, and Chapter 17, GUI Components: Part 2, you’ll learn how to build Java GUIs and how to build event handlers to respond to user interactions. The event handlers are declared in classes that implement an appropriate event-listener interface. Each event-listener interface specifies one or more methods that must be implemented to respond to user interactions. |
SwingConstants |
Contains constants used in GUI programming to position GUI elements on the screen. We explore GUI programming in Chapters 11 and 17. |