Method Overriding: Choosing the Method Body
A notification system might send email notices and ordinary notices through the same method name. Each kind of notice needs its own behaviour, while calling code should still be able to request send(). Method overriding provides this connection. The examples here use Java and focus on recognizing an override, tracing a call, and reusing a superclass implementation.
Recognize an override
Method overriding occurs when a subclass supplies its own implementation of an inherited instance method. An instance method belongs to an object rather than being declared static.
In the examples below, an override has the same method name, parameter types in the same order, and return type as the inherited method. Parameter names may differ. Java also permits some compatible reference return types, but changing a return type alone does not create a different method signature.
class Notice {
public String send() {
return "Notice queued";
}
}
class EmailNotice extends Notice {
@Override
public String send() {
return "Email queued";
}
}The annotation @Override asks the compiler to check that send() really overrides another method. It does not cause the overriding behaviour; the matching declarations do that.
These nearby cases have different meanings:
Declaration or change | Consequence in Java |
|---|---|
Matching inherited instance method with compatible return type and access | Can form an override |
Same name with different parameter types | Creates a different method, rather than overriding that declaration |
Matching superclass method declared private | Does not override that private method |
Matching superclass method declared final | Cannot override it |
Matching methods declared static | Uses method hiding rather than overriding |
An overriding method also cannot reduce access: a public inherited method must remain public.
Determine which body runs
Runtime dispatch is the selection of an overridden instance-method implementation using the actual object's class when a call executes.
For an ordinary overridden instance-method call, use the actual object's class to find the implementation.
Notice notice = new EmailNotice();
System.out.println(notice.send());The variable is declared as Notice, but the object was created as an EmailNotice. The call therefore prints Email queued. The declared type lets the compiler check that the method can be called; it does not force the superclass body to run.
If the actual object's class does not declare an override, look upward through its superclasses for the nearest implementation. You do not automatically jump to the oldest ancestor.
Reuse superclass behaviour with super
Inside an overriding method, super.send() selects the superclass implementation. This lets you extend existing behaviour instead of rewriting it.
Example: An email notice can retain the superclass message and append a delivery detail:
@Override
public String send() {
return super.send() + "; email delivery requested";
}Here super.send() returns Notice queued, and the overriding method appends the extra text. Calling send() without super from inside this same method would call the override again, repeatedly, rather than selecting the superclass body.
When tracing code, record each method entry separately. Identify the body selected, follow any super call, and then return to finish the overriding body. A superclass result is only an intermediate result when the override modifies it afterward.
What to remember
- An override replaces inherited instance-method behaviour for subclass objects.
- Check the method name, parameter types, return compatibility, and access.
- The actual object determines an ordinary overridden call's implementation.
- super selects superclass behaviour without changing the actual object.
Example: Estimating Print-Job Time
A print shop uses the following Java classes to estimate processing time in whole minutes. The model assigns a fixed setup time and a per-page time. Colour jobs add one minute per page. These are scheduling estimates rather than measured machine speeds.
class PrintJob {
public int minutes(int pages) {
return 4 + 2 * pages;
}
}
class ColourJob extends PrintJob {
@Override
public int minutes(int pages) {
return super.minutes(pages) + pages;
}
}
class BasicJob extends PrintJob {
}An explicit superclass call uses super to select a method implementation from the superclass chain. Here super.minutes(pages) supplies the ordinary estimate before the colour adjustment is added.
a) When ColourJob.minutes(8) reaches super.minutes(8), what value does that superclass call return?
- The expression super.minutes(8) selects PrintJob.minutes and passes 8 as the page count.
- The per-page contribution is 2 min/page×8 pages, giving ________. Add the fixed setup time of 4 minutes.
The superclass call returns 20, representing 20 minutes. This is the result of the superclass call, before the overriding method finishes.
b) What does the following code print, and which method body runs first?
PrintJob job = new ColourJob();
System.out.println(job.minutes(8));- The actual object is a ColourJob, so the ordinary call first enters ColourJob.minutes, even though the variable is declared as PrintJob.
- The super call supplies the 20-minute estimate calculated in part a. The colour adjustment is one minute for each of 8 pages, giving ________.
- Return to the overriding body and add the adjustment.
The override continues after the superclass call returns. Stopping at the superclass estimate would leave out the colour adjustment.
The statement prints 28, representing 28 minutes; ColourJob.minutes runs first.
c) What does the following code print, given that BasicJob does not declare its own minutes method?
PrintJob job = new BasicJob();
System.out.println(job.minutes(6));- The actual object is a BasicJob. It declares no override, so look to its superclass for the nearest implementation: PrintJob.minutes.
- Substitute 6 pages into that implementation. The per-page contribution is 2 min/page×6 pages=12 min.
- Add the fixed setup time.
There is no colour adjustment because this object uses the inherited PrintJob implementation. The statement prints 16, representing 16 minutes.
An online checkout creates receipts. In this Java template, TYPE is a placeholder for the return type of the overriding method.
class Receipt { }
class EmailReceipt extends Receipt { }
class Checkout {
public Receipt createReceipt() {
return new Receipt();
}
}
class EmailCheckout extends Checkout {
@Override
public TYPE createReceipt() {
return new EmailReceipt();
}
}To make the override declare the most specific return type available in this class relationship, replace TYPE with .
A parking application calculates charges in whole cents using the Java classes below. What number does the final statement print? Answer in cents, to the nearest whole cent.
class ParkingRate {
public int cents(int hours) {
return 140 * hours;
}
}
class DiscountRate extends ParkingRate {
@Override
public int cents(int hours) {
if (hours >= 4) {
return super.cents(hours) - 125;
}
return super.cents(hours);
}
}ParkingRate rate = new DiscountRate();
System.out.println(rate.cents(5));