Is it possible to create an instance of an interface in Java?
Somewhere I have read that using inner anonymous class we can do it as shown below:
interface Test { public void wish(); } class Main { public static void main(String[] args) { Test t = new Test() { public void wish() { System.out.println("output: hello how r u"); } }; t.wish(); } }
cmd> javac Main.java cmd> java Main output: hello how r u
Is it correct here?
You cannot create instances of a Java interface by itself. You must always create an instance of some class that implements the interface, and reference that instance as an instance of the interface.
You cannot create an instance of an interface , because an interface is basically an abstract class without the restriction against multiple inheritance. And an abstract class is missing parts of its implementation, or is explicitly marked as abstract to prohibit instantiation.
If a type implements two interfaces, and each interface define a method that has identical signature, then in effect there is only one method, and they are not distinguishable. If, say, the two methods have conflicting return types, then it will be a compilation error.
If two interfaces contain a method with the same signature but different return types, then it is impossible to implement both the interface simultaneously. According to JLS (§8.4. 2) methods with same signature is not allowed in this case.
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,
public interface A { } public class B implements A { } public static void main(String[] args) { A test = new B(); //A test = new A(); // wont compile }
What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type interface Test
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With