This is one of the frequently asked interview question. No, We cannot have a Constructor defined in an Interface. A method in a interface will be public and abstract by default to provide 100% abstraction and the implementation(method body) will be provided by the implementing class.In this article we will get to know why Constructors are not allowed in Interface.
Lets take a look into the below example
public interface Manipulation{ public int add(int a, int b); } public class Logic implements Maniputlation{ public int add(int a, int b){ int c= a+b; return c; } public static void main(Sring args[]) { Logic l= new Logic(); System.out.println(l.add(1,2)); }
In the above code we have a interface “Manipulation” which defines a method add(), whose implementation is provided by the class “Logic”.
In order to call a method we need object, since the methods in the interface doesn’t have body there is no need for calling the methods in the Interface. Since we cannot call the methods in the interface, there is no need for creating object for the interface and there is no need for having a constructor in it(Constructors will be called during object creation).Constructors belongs to implementations. An interface, on the other hand is a “contract” for a class that implements it.
Leave a Reply