Sub topic 12
Default Methods
Suppose many classes already implement an interface, and you want to add a new method to it. Each of those classes would break, because each would be missing the new method. Java 8 solved this problem with default methods.
What Is a Default Method?
A default method is an interface method that has a body. You mark it with the keyword default. A class that implements the interface gets this method for free. The class may still override it if it needs different behavior.
An abstract method is a promise: "every class must write this." A default method is a ready-made answer: "here is a version you can use as it is."
A Worked Example
The Greeter interface below has 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!
}
}Look at what each class does:
EnglishGreeterwrites onlyname(). It uses the defaultgreet()without changes.PirateGreeterwritesname()and also overridesgreet(). Its own version replaces the default.
The default method calls name(), which is abstract. This works because any real object will have a name() method. Default methods are often built from the interface's abstract methods in this way.
How Java Picks the Method
When you call greet(), Java first checks the object's class. If the class has its own version, Java runs that version. If not, Java runs the default.
Rules to Remember
| Rule | Why it matters |
|---|---|
| A default method needs the `default` keyword and a body | Without a body, it would be an abstract method |
| Default methods are public | An override must also be `public` |
| A default method cannot use instance fields | Interfaces have no instance fields to use |
| A class may override a default | Overriding lets a class change the behavior |
Exercises
Exercise
Add a default method String farewell() to Greeter that returns "Goodbye, " followed by the name. Which classes must change for the program to still compile?
Show answer
No class has to change. Add default String farewell() { return "Goodbye, " + name(); } to the interface. Both EnglishGreeter and PirateGreeter inherit it automatically, which is why default methods exist.
Exercise
In PirateGreeter, what happens if you write String greet() without the public keyword?
Show answer
The code fails to compile. Interface methods are public, and an override cannot be less visible than the method it overrides.