Sub topic 12
Default Methods
Suppose many classes already implement an interface, and you want to add a new method to it. Before Java 8, every one of those classes would stop compiling until someone wrote the new method in each of them. Default methods fix this problem.
A default method is a method in an interface that has a body. It starts with the keyword default. Any class that implements the interface gets this method for free. The class can keep the default version, or it can replace it with its own.
Why Default Methods Exist
An interface is like a contract. Every abstract method in it is a promise that each implementing class must keep. If you add a new abstract method, you add a new promise, and every old class breaks the contract.
Java 8 needed to add new methods to interfaces that millions of programs already used, such as List and Collection. Breaking all that code was not an option, so the Java team added default methods. A default method lets an interface grow without forcing every class to change.
Here are the terms this chapter uses:
- An abstract method is a method with no body. Classes must supply the body.
- A default method is a method with a body, marked
default. Classes may use it as is. - To override a method is to write your own version of it in a class, which replaces the inherited one.
Your First Default Method
This example has an interface with one abstract method and one default method.
interface Greeter {
String name();
default String greet() {
return "Hello, " + name() + "!";
}
}
class EnglishGreeter implements Greeter {
@Override
public String name() {
return "Sam";
}
}
class PirateGreeter implements Greeter {
@Override
public String name() {
return "Jack";
}
@Override
public String greet() {
return "Ahoy, " + name() + "!";
}
}
public class Main {
public static void main(String[] args) {
Greeter a = new EnglishGreeter();
Greeter b = new PirateGreeter();
System.out.println(a.greet()); // prints: Hello, Sam!
System.out.println(b.greet()); // prints: Ahoy, Jack!
}
}Let's walk through it.
Greeterdeclaresname()with no body. Every class must write it.greet()has a body and the worddefault. Classes do not have to write it.EnglishGreeterwrites onlyname(). When you callgreet(), Java runs the default version.PirateGreeterwrites both methods. Its owngreet()replaces the default.
Look at how the default greet() calls name(). A default method can call the other methods of its interface, including abstract ones. When the program runs, Java calls the version of name() that belongs to the real object.
How Java Picks Which Version Runs
When you call a method on an object, Java first checks the object's class. If the class has its own version, that version runs. If not, Java uses the default from the interface.
People often sum this up as "the class wins." A method written in a class, or inherited from a superclass, always beats a default from an interface.
Growing an Interface Safely
Here is the main reason default methods exist. Say version 1 of a library had this interface:
interface Counter {
int count();
}Many users wrote classes like ClickCounter. In version 2, the library authors want an isZero() check. If they add it as an abstract method, every user's class breaks. They add it as a default method instead:
interface Counter {
int count();
default boolean isZero() {
return count() == 0;
}
}
class ClickCounter implements Counter {
private int clicks;
void click() {
clicks++;
}
@Override
public int count() {
return clicks;
}
}
public class Main {
public static void main(String[] args) {
ClickCounter c = new ClickCounter();
System.out.println(c.isZero()); // prints: true
c.click();
System.out.println(c.isZero()); // prints: false
}
}ClickCounter did not change at all, yet it now has isZero(). Old code keeps compiling and gets the new feature.
Building On the Default Instead of Replacing It
Sometimes you want to add to the default rather than throw it away. Inside your override, write InterfaceName.super.methodName() to call the default version.
interface Greeter {
String name();
default String greet() {
return "Hello, " + name() + "!";
}
}
class FriendlyGreeter implements Greeter {
@Override
public String name() {
return "Ana";
}
@Override
public String greet() {
return Greeter.super.greet() + " Nice to meet you.";
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new FriendlyGreeter().greet());
// prints: Hello, Ana! Nice to meet you.
}
}This form looks odd at first. Plain super.greet() would mean the superclass's method, so Java needs the interface name to know which greet() you mean. A later chapter uses the same form to fix clashes between two interfaces.
Rules and Limits
| Rule | What it means |
|---|---|
| Must use the `default` keyword | Without it, a method with a body in an interface does not compile (unless it is `static` or `private`). |
| Always public | Like all interface methods, a default method is public. An override must also be `public`. |
| No instance fields | Interfaces cannot hold per-object data, so a default method can only work through other methods. |
| Cannot redefine `Object` methods | You cannot write a default `toString()`, `equals()`, or `hashCode()`. The class always wins, so such a default would never run. |
| Class wins | A method in the class or its superclass beats any default. |
Common Beginner Mistakes
- Forgetting
default. A method body in an interface withoutdefaultdoes not compile. - Trying to use a field.
default void reset() { clicks = 0; }fails, because the interface has noclicksfield. Any variable declared in an interface is a constant, which cannot be changed. - Dropping
publicin the override. The compiler rejects it. - Expecting the default to beat the class. If a superclass already has a method with the same signature, that method runs, not the default.
Exercise
An interface Shape has an abstract method double area() and a default method String size() that returns "big" if area() is greater than 10, else "small". Class Dot implements only area() and returns 1.0. Class Field implements area() returning 500.0 and overrides size() to return "huge". What do new Dot().size() and new Field().size() return?
Show answer
new Dot().size() returns "small". Dot does not override size(), so the default runs, and 1.0 is not greater than 10. new Field().size() returns "huge", because Field overrides size() and the class wins over the default.
Exercise
Write a default method describe() for this interface that returns the text "Item: " followed by the result of label(). Then show how a class could override describe() so it adds " (sale)" to the end of the default text.
interface Item { String label(); }
Show answer
Inside the interface add: default String describe() { return "Item: " + label(); }. In the class, override it as @Override public String describe() { return Item.super.describe() + " (sale)"; }. The Item.super.describe() call runs the default version, and the class then adds its own text.
Exercise
Why does this code fail to compile? interface Timer { int seconds = 0; default void tick() { seconds++; } }
Show answer
Every variable declared in an interface is implicitly public, static, and final, so seconds is a constant. seconds++ tries to change a final value, which is not allowed. Interfaces cannot hold changing per-object state. Put the field in a class, or use an abstract class.