Interface in Java

Interface in Java


An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve abstraction and multiple inheritance in Java.
Java Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.
  • It is used to achieve abstraction.
  • By interface, we can support the functionality of multiple inheritance.
  • It can be used to achieve loose coupling.


Java Interface Example

In this example, Printable interface has only one method, its implementation is provided in the A class.
  1. interface A{  
  2. void print();  
  3. }  
  4. interface B{  
  5. void disp();  
  6. }  
  7. class C implements  A,B
  8. {  
  9. public void print()
  10. {
  11. System.out.println("print Hello");
  12. }  
  13.   
  14. public void disp()
  15. {
  16. System.out.println("display Hello");

  17. }  
  18. public static void main(String args[]){  
  19. C obj = new C();  
  20. obj.print();  
  21.  }  
  22. Output:
    print Hello 
  23. display Hello
  24. 
    
Previous
Next Post »