
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create Object for an Interface in Java
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
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
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