Skip to main content

Interface in Java


Interface:

         An interface is a nothing but  reference type,it is same as class.In short Interface is collection of Abstract Method .
         It can  also contain final, static fields .
           

  1.   you can't create object of Interface.
  2.    it can't have Constructor.
  3.   Interface can't implement another interface it can extend another one.
  4. Interface not extended by class but implemented.

Declare Interface:

public interface Example {
    //final, static fields .
    //Method

}

Example
1.create interface that contain method.


public interface IA {
    public void show();

}

2.implement by class

 public class ClassA  implements IA{

    @Override
    public void show() {
        System.out.println("from class A called");
    }
    
}

3.create object and run it.

public class TestClass {

    public static void main(String[] args) {
         IA demo = new ClassA();
        demo.show();
      
    }


}
4.Result:


   from class A called

Extend Interface: 

you can extend multiple interface 
like interface A extend B,C

Example:

1.create interface that contain method.


public interface IB  extend IA{
    public void showBclass();

}

.2.implement by class

 public class ClassB  implements IB{

    @Override
    public void show() {
        System.out.println("from class B called");
    }
@Override
 public void showBclass(){
System.out.println("from class B called ShowBclass");
}
    
}

3.create object and run it.

public class TestClass {

    public static void main(String[] args) {
         IB demo = new ClassB();
        demo.show();
       demo.showBclass();
      
    }


}
4.Result:

 from class B called
from class B called showBclass





Comments