Definition-
Interface is a 100% abstract class.
– All methods in interface are public and abstract.
-All data members in interface are public, static and final.
– multiple inheritance is allowed in interfaces.
Note 1- class ‘implements’ interface
Note 2- interface ‘extends’ interface
Code samples are here
1- One class can implements multiple interfaces
a-
package intrfc; public interface X { void show(); }
b-
package intrfc; public interface Y { void display(); }
c-
package intrfc; public class Z implements X,Y { @Override public void display() { System.out.println("bye"); } @Override public void show() { System.out.println("hi"); } public static void main(String[] args) { Z z=new Z(); z.show(); z.display(); } }
2- Interface can extend other interface
a-
package intrfc; public interface X1 { void show(); }
b-
package intrfc; public interface Y1 extends X1 { void display(); }
c-
package intrfc; public class Z1 implements Y1 { @Override public void display() { System.out.println("bye"); } @Override public void show() { System.out.println("hi"); } public static void main(String[] args) { Z1 z=new Z1(); z.show(); z.display(); } }
After Java 7 –
1- Interface’s default methods –
public interface Person{ default String getName(){ return “kuldeep kaushik”; } }
Rules of interface’s default methods-
- If the class already has the same method as an Interface, then the default method from the implemented Interface does not take effect.
- If one interface inherits another interface and both of them implement a default method, the default method of the child interface would be used by an implementing class.
- An explicit call to an interface default method can be made from inside an implementing class using super. For example Interface.super.defaultMethod()
1- Interface’s static methods –
public interface Test{ static String getStaticNumber(){ return 1; } }