Java Interface Example


Java interface

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.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.

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.







  1. interface Printable
  2. {  
  3. void print();  
  4. }  
  5. interface Showable
  6. {  
  7. void show();  
  8. }  
  9. class A implements Printable,Showable
  10. {  
  11. public void print()
  12. {
  13. System.out.println("Hello");
  14. }  
  15. public void show()
  16. {
  17. System.out.println("Welcome");
  18. }  
  19.   public static void main(String args[])
  20. {  
  21. A obj = new A();  
  22. obj.print();  
  23. obj.show();  
  24.  }  
  25. }  

Comments