One Call, Different Object Behaviours
Polymorphism lets you use a common reference type to work with objects that provide different behaviours for the same operation. You meet it when one collection contains several kinds of objects, yet the code processing that collection makes the same method call on each one. This lesson focuses on runtime polymorphism: selecting an instance method's implementation according to the object receiving the call.
One operation, several implementations
Suppose a messaging application represents different notices through a common Notice type. The class definitions below supply the behaviour of text() for each kind of notice.
class Notice {
String text() {
return "General";
}
}
class EmailNotice extends Notice {
String text() {
return "Email";
}
}
class SmsNotice extends Notice {
String text() {
return "Text";
}
}Example: Inside a method, you can write the following statements:
Notice current = new EmailNotice();
System.out.println(current.text());The variable's declared type is Notice, but the object created by new EmailNotice() has runtime class EmailNotice. The program prints Email. Assigning the object to a Notice reference does not create a separate Notice object or remove its specialised behaviour.
Dynamic dispatch is the runtime selection of the method implementation for the receiving object. For the ordinary Java instance methods used here, the governing idea is:
If the runtime class supplies the matching implementation, that body runs. Otherwise, selection uses the nearest matching implementation inherited from an ancestor. An object does not need a newly written implementation in its own class to participate in polymorphism.
What is checked and what is selected
Two separate questions explain the apparent tension between a general reference and specialised behaviour. The compiler checks whether the call is permitted through the reference's declared type. During execution, the object's runtime class determines which implementation handles that permitted call.
Question | Information used | Effect |
|---|---|---|
Is current.text() available? | Declared type Notice | The call is permitted because Notice provides text() |
Which text() body runs? | Runtime class EmailNotice | The specialised email implementation runs |
Is an unrelated extra method available? | Declared type Notice | The object's extra methods are not automatically exposed through this reference |
The runtime class selects behaviour only after the method call is valid through the declared type. Dynamic dispatch does not make every method on the actual object accessible through every reference to it.
Reading a polymorphic collection
Inside a method, a collection can hold references to several runtime classes:
Notice[] notices = {
new EmailNotice(),
new SmsNotice(),
new Notice()
};
for (Notice notice : notices) {
System.out.println(notice.text());
}The output is Email, then Text, then General. Each iteration uses a reference declared as Notice. Nevertheless, the receiver changes, so the selected implementation can change too. The loop does not need a separate branch naming each notice class.
This design lets a new kind of notice work with the same loop when it supports the existing operation. The new class still needs suitable behaviour, but the client can continue requesting text() through Notice.
Trace each call using the object referenced at that moment. Keep this runtime selection separate from choosing among methods with different parameter lists. In C++, virtual functions support this form of runtime selection; the examples here use Java's ordinary overridable instance methods.
What to remember
- The declared reference type determines which calls are available.
- The runtime class determines the selected implementation of an overridable instance method.
- An inherited implementation is used when no closer class supplies one.
- A shared client can request the same operation from different kinds of objects.
Example: Pricing a Notification Batch
A notification service calculates a batch's sending cost in whole cents. A dispatch trace records which method implementation each call selects. Use one to follow the Java code below; each cents() method returns the cost of sending one notification.
class Notification {
int cents() {
return 2;
}
}
class EmailNotification extends Notification {
int cents() {
return 1;
}
}
class TextNotification extends Notification {
int cents() {
return 5;
}
}
class Billing {
static int batchCost(Notification[] batch) {
int total = 0;
for (Notification notification : batch) {
total += notification.cents();
}
return total;
}
}The following batch is created inside a client method:
Notification[] batch = {
new EmailNotification(),
new TextNotification(),
new EmailNotification(),
new Notification()
};a) For the second array element, identify the selected method implementation and its returned cost.
First, separate the reference type from the object's class. The loop variable's declared type is ________, which provides cents() and therefore permits the call.
For the second element, the object's runtime class is ________. Dynamic dispatch selects that class's matching method body. Assigning the object to the loop variable does not change its runtime class.
The selected implementation is TextNotification.cents(), and it returns 5 cents.
b) Calculate the cost returned by Billing.batchCost(batch) for the original batch.
Read the objects in array order. The two email objects each select EmailNotification.cents() and return 1 cent. The text object returns 5 cents, and the ordinary notification returns 2 cents.
The two email notifications contribute ________ altogether. The text notification and ordinary notification contribute ________ altogether.
Add all four returned costs:
The loop returns 9 cents. The declared array element type does not make every call use the base implementation. Each iteration selects behaviour using its current object.
c) A developer adds the class below and creates an expanded batch containing the original four objects followed by two new AppNotification objects. Find the expanded batch's cost and decide whether the body of batchCost needs to change.
class AppNotification extends Notification {
int cents() {
return 3;
}
}Each new object is an AppNotification, so its call selects AppNotification.cents() and returns 3 cents. The two added objects contribute ________.
The original four objects still contribute 9 cents. Therefore:
The expanded batch costs 15 cents, and the body of batchCost needs no change. Its existing loop already calls an operation available through Notification. The added objects supply their own implementation of that operation, so the same client code handles them.
A school notification system uses the following Java classes. Its client code should support additional kinds of channel without adding a separate branch for each class.
class Channel {
void transmit(String message) {
System.out.println("General: " + message);
}
}
class EmailChannel extends Channel {
@Override
void transmit(String message) {
System.out.println("Email: " + message);
}
}
class TextChannel extends Channel {
@Override
void transmit(String message) {
System.out.println("Text: " + message);
}
}Complete both blanks using identifiers from the code. Use the most general declared class that accepts objects of either channel subclass.
The parameter named channel in a method named deliver should have declared type . Inside deliver, the shared method name to call on channel, passing message, is .
A monitoring program calls reading() once on each object in this Java array, from left to right. Complete the table with the exact integer returned at each position. The array statements run inside a method.
class Sensor {
int reading() {
return 4;
}
}
class OutdoorSensor extends Sensor {
int reading() {
return 9;
}
}
class RoofSensor extends OutdoorSensor {
}
class IndoorSensor extends Sensor {
int reading() {
return 6;
}
}Sensor[] sensors = {
new Sensor(),
new RoofSensor(),
new IndoorSensor(),
new OutdoorSensor()
};| Position | Object class | Returned integer |
| 1 | Sensor | |
| 2 | RoofSensor | |
| 3 | IndoorSensor | |
| 4 | OutdoorSensor |