Default Methods
suggest changeVersions
Java SE 8. Java SE 9 was early access when this topic was written. Default methods were added in Java 8.
Introduction
Default methods, introduced in Java 8, add a method to an interface without breaking existing implementors. The interface supplies an implementation used when a class does not implement that method.
Syntax
- public default void methodName() {/* method body */}
Remarks
Default methods
- A default method adds behavior without forcing existing implementors to implement it.
- A class or sub-interface can override it.
- A default method cannot override a method from
java.lang.Object. - If a class inherits default methods with the same signature from more than one interface, it must override the method and provide its own body.
- A class that already has a static method with the same signature as a new default method fails to compile. The same kind of clash happens when a superclass gains an instance method that clashes with a subclass static method.
Static methods
- An interface static method is mainly a utility for the interface's other methods.
- Implementing classes do not inherit it. It is called through the interface name. A class may declare its own static method with the same signature; that does not override the interface method.
- It cannot have the same signature as an instance method of
java.lang.Object.
A subclass method interacts with a superclass method of the same signature as follows:
| Superclass instance method | Superclass static method | |
|---|---|---|
| Subclass instance method | overrides | compile-time error |
| Subclass static method | compile-time error | hides |
An implementing class interacts with an interface method of the same signature as follows. An interface static method is not inherited, so a class method neither overrides nor hides it:
| Interface default method | Interface static method | |
|---|---|---|
| Class instance method | overrides | unrelated; call the static method on the interface |
| Class static method | compile-time error | unrelated; call the static method on the interface |
References :
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents