Java Default Methods in Interfaces
A default method is an interface method with a body. Every implementing class receives it unless it writes its own version.
Two implementers share one default line
Neither class writes the method. Both print the default line.
public class Main {
public static void main(String[] args) {
Greeter email = new EmailSender();
Greeter sms = new SmsSender();
email.greet();
sms.greet();
}
}
interface Greeter {
default void greet() {
System.out.println("Hello, and welcome.");
}
}
class EmailSender implements Greeter {
}
class SmsSender implements Greeter {
}An override replaces the default line
One implementer writes its own greet method. Its own line prints instead.
public class Main {
public static void main(String[] args) {
Greeter phone = new PhoneSender();
phone.greet();
}
}
interface Greeter {
default void greet() {
System.out.println("Hello, and welcome.");
}
}
class PhoneSender implements Greeter {
public void greet() {
System.out.println("Hello, calling you now.");
}
}The default runs through an interface variable
The variable type is the interface. The object still receives the default body.
public class Main {
public static void main(String[] args) {
Greeter sender = new EmailSender();
sender.greet();
}
}
interface Greeter {
default void greet() {
System.out.println("Hello, and welcome.");
}
}
class EmailSender implements Greeter {
}Example
public class Main {
public static void main(String[] args) {
Notifier email = new EmailNotifier();
Notifier phone = new PhoneNotifier();
email.notifyUser();
phone.notifyUser();
}
}
interface Notifier {
default void notifyUser() {
System.out.println("You have a message.");
}
}
class EmailNotifier implements Notifier {
}
class PhoneNotifier implements Notifier {
public void notifyUser() {
System.out.println("You have a missed call.");
}
}Key points
- A default method arrives in every implementing class for free.
- An implementer may override a default method with its own body.
- The default body runs only when no override replaces it.
- Shared state and constructors point to an abstract class.
- A capability many unrelated classes can carry points to an interface.
In this example, the email notifier keeps the default line, while the phone notifier overrides it with its own line.
Note
Default methods let an interface grow without breaking its old implementers.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A class implements an interface but does not write its default method. What happens when the method is called?