
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
Define Constructor Inside an Interface in Java
No, you cannot have a constructor within an interface in Java.
You can have only public, static, final variables and, public, abstract, methods as of Java7.
From Java8 onwards interfaces allow default methods and static methods.
From Java9 onwards interfaces allow private and private static methods.
Moreover, all the methods you define (except above mentioned) in an interface should be implemented by another class (overridden). But, you cannot override constructors in Java.
Still if you try to define constructors in an interface it generates a compile time error.
Example
In the following Java program, we are trying to define a constructor within an interface.
public interface MyInterface{ public abstract MyInterface(); /*{ System.out.println("This is the constructor of the interface"); }*/ public static final int num = 10; public abstract void demo(); }
Compile time error
On compiling, the above program generates the following error
Output
MyInterface.java:2: error: expected public abstract MyInterface(); ^ 1 error
In short, it does not accept methods without return type in an interface. If you add return type to the MyInterface() method then it is considered as a normal method and the program gets compiled without errors.
public interface MyInterface { public abstract void MyInterface(); public static final int num = 10; public abstract void demo(); }