Image

Java - Core Java - Interface

Interface

When we have multiple solutions to solve the same problem in that case we should go for interface.

Using the keyword interface, you can fully abstract class interface from its implementation. That is using interface you can specify what a class must do, but not how it does it. Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body.

Why do we use interface?
  • It is used to achieve 100% abstraction.
  • Java does not support multiple inheritance in case of class, but by using interface it can achieve multiple inheritance.
  • It is also used to achieve loose coupling.
  • Interfaces are used to implement abstraction.
  • Abstract classes may contain non-final variables, whereas variables in interface are final, public and static.
  • In practice, this means that you can define interfaces which don’t make assumptions about how they are implemented. Once it is defined, any number of classes can implement an interface. Also, one class can implement any number of interfaces.

    Interfaces are basically used to develop user defined data types.

    Syntax for defining an interface:
    interface 
    {
    Variable declaration;
    Method declaration;
    }
    
    For Example
    public interface ABC4 {
      void show();
    }
    
    class xyz implements ABC4
    { public void show() {
          System.out.println("i am in abc"); 
      }
      public static void main(String[] args) {
        ABC4 z=new xyz();
        z.show();
      }
    }
    
    Program to achieve multiple inheritance
    interface Abc
    {
      public void show();
    }
    class Pqr
    {
        static int i=20;
    }
    class Xyz implements Abc extends Pqr {
        public void show()
        {
          System.out.println("I m in abc");
        }
     
        public static void main(String[] args) {
            Abc a;
            Xyz z=new Xyz();
            a=z;
            a.show();
            System.out.println(i);         
        }  
    }