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.


  1. All methods in an interface are implicitly public and An interface cannot be instantiated. A Java class can implement multiple Java Interfaces.
  2. An interface can extend from one or many interfaces. 
  3. A class can extend only one class but implement any number of interfaces
  4. An interface cannot implement another Interface. It has to extend another interface if needed.
  5. It is necessary that the class must implement all the methods declared in the interfaces.
  6. The class should override all the abstract methods declared in the interface

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();   

}  

}

 

 

 

Hi, Welcome to etechvidya