Can we create an object for an interface in java?

Java 8Object Oriented ProgrammingProgramming

No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete.

Still if you try to instantiate an interface, a compile time error will be generated saying “MyInterface is abstract; cannot be instantiated”.

In the following example we an interface with name MyInterface and a class with name InterfaceExample.

In the interface we have an integer filed (public, static and, final) num and abstract method demo().

From the class we are trying to − create an object of the interface and print the num value.

Example

 Live Demo

interface MyInterface{
   public static final int num = 30;
   public abstract void demo();
}
public class InterfaceExample implements MyInterface {
   public void demo() {
      System.out.println("This is the implementation of the demo method");
   }
   public static void main(String args[]) {
      MyInterface interfaceObject = new MyInterface();
      System.out.println(interfaceObject.num);
   }
}

Compile time error

On compiling, the above program generates the following error

Output

InterfaceExample.java:13: error: MyInterface is abstract; cannot be instantiated
   MyInterface interfaceObject = new MyInterface();
^
1 error

To access the members of an interface you need to implements it and provide implementation to all the abstract methods of it.

Example

 Live Demo

interface MyInterface{
   public int num = 30;
   public void demo();
}
public class InterfaceExample implements MyInterface {
   public void demo() {
      System.out.println("This is the implementation of the demo method");
   }
   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.demo();
      System.out.println(MyInterface.num);
   }
}

Output

This is the implementation of the demo method
30
raja
Published on 04-Jul-2019 16:55:52
Advertisements