Font Awesome Icons

Tutorial

Interface in Java

  • An interface is just like Java Class, but it only has static constants and abstract method. Java uses Interface to implement multiple inheritance. A Java class can implement multiple Java Interfaces.

  • All methods in an interface are implicitly public and An interface cannot be instantiated. A Java class can implement multiple Java Interfaces. It is necessary that the class must implement all the methods declared in the interfaces.

  • The class should override all the abstract methods declared in the interface

  • An interface can extend from one or many interfaces. A class can extend only one class but implement any number of interfaces

  • An interface cannot implement another Interface. It has to extend another interface if needed.

To use an interface in your class, append the keyword “implements” after your class name followed by the interface name.

  • An interface which is declared inside another interface is referred to as the nested interface.

  • At the time of declaration, the interface variable must be initialized. Otherwise, the compiler will throw an error.

 

Example of an Interface in Java:

 

interface MyInterface

{       

public void method1();   

public void method2();

}

class Demo implements MyInterface

{   

public void method1()   

System.out.println(“implementation of method1”);   

}   

public void method2()   

System.out.println(“implementation of method2”);   

}   

public static void main(String arg[])   

MyInterface obj = new Demo(); 

obj.method1();   

}

}

 

Inheritance with the interface:

interface Inf1

{   

public void method1();

}

interface Inf2 extends Inf1

{   

public void method2();

}

public class Demo implements Inf2

{        

public void method1()

System.out.println(“method1”);    

}    

public void method2()

System.out.println(“method2”);    

}    

public static void main(String args[])

Inf2 obj = new Demo(); 

obj.method2();    

}

}

 

Multiple inheritance  with Interface

interface C1

{  

void work();  

}  

interface D1

{  

void work();  

}       

class I4 implements C1,D1

{  

public void work()

System.out.println(“MULTIPLE INHERITANCE”); 

}  

public static void main(String args[])

{   

I4 obj = new I4();  

obj.work();   

}  

}