- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can we 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(); }
- Related Articles
- Can we define an interface inside a Java class?
- Can we define a class inside a Java interface?
- Can we define a static constructor in Java?
- Can we define an enum inside a class in Java?
- Can we define an enum inside a method in Java?
- Can we define a parameterized constructor in an abstract class in Java?
- Can we define constant in class constructor PHP?
- Can we declare an interface with in another interface in java?
- Can we create an object for an interface in java?
- Can we overload methods of an interface in Java?
- Can we declare an interface as final in java?
- Why can't we define a static method in a Java interface?
- What happens if we define a concrete method in an interface in java?
- Can we write an interface without any methods in java?
- Can we use private methods in an interface in Java 9?
