When
you extend an interface that contains default methods you have 3
possibilities.
1. If
interface 'B' extend interface 'A', and not providing the
implementations for default methods in A, then extended interface
'B' inherit the default method.
interface A{ void print(); default void show(){ System.out.println("I am in show"); } }
interface B extends A{ void display(); }
class C implements B{ public void display(){ } public void print(){ } }
class Test{ public static void main(String args[]){ C obj1 = new C(); obj1.show(); } }
Output
I am in show
2. If
interface 'B' extend interface 'A', and re-declare the default
methods, then default methods became abstract.
interface A{ void print(); default void show(){ System.out.println("I am in show"); } }
interface B extends A{ void display(); void show(); }
Now
any class that is going to implement the interface B, has to provide
the implementation for the method show also.
class C implements B{ public void display(){ } public void print(){ } }
When
you tries to compile the above program compiler throws below error,
since class 'C' is not providing the implementation for the method
'show'.
C.java:1: error: C is not abstract and does not override abstract method show()in B class C implements B{ ^ 1 error
To
make the program works fine, add the implementation for the method
'show' in the class 'C'.
class C implements B{ public void display(){ } public void print(){ } public void show(){ System.out.println("I am in show"); } }
class Test{ public static void main(String args[]){ C obj1 = new C(); obj1.show(); } }
Output
I am in show
3. If
interface 'B' extend interface 'A', and redefine the default methods,
then default methods are overridden.
interface A{ void print(); default void show(){ System.out.println("I am in interface A"); } }
interface B extends A{ void display(); default void show(){ System.out.println("I am in interface B"); } }
class C implements B{ public void display(){ } public void print(){ } }
class Test{ public static void main(String args[]){ B obj1 = new C(); A obj2 = obj1; obj2.show(); } }
Output
I am in interface B
No comments:
Post a Comment