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.
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); } }
On compiling, the above program generates the following error
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.
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); } }
This is the implementation of the demo method 30