Introduction
Default Method introduced in Java 8, allows developers to add new methods to an interface without breaking the existing implementations of this interface. It provides flexibility to allow the interface to define an implementation which will be used as default when a class which implements that interface fails to provide an implementation of that method.
Syntax
- public default void methodName() {/* method body */}
Default methods
-
Can be used within an interface, to introduce a behaviour without forcing existing subclasses to implement it.
-
Can be overridden by subclasses or by a sub-interface.
-
Are not allowed to override methods in java.lang.Object class.
-
If a class implementing more than one interface, inherits default methods with identical method signatures from each of the intefaces, then it must override and provide its own interface as if they were not default methods (as part of resolving multiple inheritance).
-
Although are intended to introduce a behaviour without breaking existing implementations, existing subclasses with a static method with same method signature as the newly introduced default method will still be broken. However this is true even in case of introducing an instance method in a superclass.
Static methods
-
Can be used within an interface, primarily intended to be used as a utility method for default methods.
-
Cannot be overridden by subclasses or by a sub-interface (is hidden to them).
However as is the case with static methods even now, each class or interface can have its own.
-
Are not allowed to override instance methods in java.lang.Object class (as is presently the case for subclasses as well).
Below is a table summarizing the interaction between sub-class and super-class.
- | SUPER_CLASS-INSTANCE-METHOD | SUPER_CLASS-STATIC-METHOD |
---|
SUB_CLASS-INSTANCE-METHOD | overrides | generates-compiletime-error |
SUB_CLASS-STATIC-METHOD | generates-compiletime-error | hides |
Below is a table summarizing the interaction between interface and implementing-class.
- | INTERFACE-DEFAULT-METHOD | INTERFACE-STATIC-METHOD |
---|
IMPL_CLASS-INSTANCE-METHOD | overrides | hides |
IMPL_CLASS-STATIC-METHOD | generates-compiletime-error | hides |
References :
-
http://www.journaldev.com/2752/java-8-interface-changes-static-method-default-method
-
https://docs.oracle.com/javase/tutorial/java/IandI/override.html