Default Methods
Ex:
1) interface Interf {
2) default void m1() {
3) System.out.println("Default Method");
4) }
5) }
6) class Test implements Interf {
7) public static void main(String[] args) {
8) Test t = new Test();
9) t.m1();
10) }
11) }
Ex:
1) interface Interf {
2) default int hashCode() {
3) return 10;
4) }
5) }
CompileTimeError
Reason: Object class methods are by-default available to every Java class hence it's not required to bring through default methods. Default method vs multiple inheritanceTwo interfaces can contain default method with same signature then there may be a chance of ambiguity problem (diamond problem) to the implementation class. To overcome this problem compulsory we should override default method in the implementation class otherwise we get compile time error.
1) Eg 1:
2) interface Left {
3) default void m1() {
4) System.out.println("Left Default Method");
5) }
6) }
7)
8) Eg 2:
9) interface Right {
10) default void m1() {
11) System.out.println("Right Default Method");
12) }
13) }
14)
15)
Eg 3:
16) class Test implements Left, Right {}
How to override default method in the implementation class ?In the implementation class we can provide complete new implementation or we can call any interface method as follows.interfacename.super.m1();
Ex:
1) class Test implements Left, Right {
2) public void m1() {
3) System.out.println("Test Class Method"); // OR Left.super.m1();
4) }
5) public static void main(String[] args) {
6) Test t = new Test();
7) t.m1();
8) }
9) }
Differences between interface with default methods and abstract classEven though we can add concrete methods in the form of default methods to the interface, it won't be equal to abstract class.
interface with default method != abstract class |