Can we define constructor inside an interface in java?

Java 8Object Oriented ProgrammingProgramming

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();
}
raja
Published on 04-Jul-2019 16:59:41
Advertisements