interface TestA { String toString(); } public class Test { public static void main(String[] args) { System.out.println(new TestA() { public String toString() { return "test"; } }); } }
What is the result?
A. test
B. null
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 1.
E. Compilation fails because of an error in line 4.
F. Compilation fails because of an error in line 5.
What is the answer of this question and why? I have one more query regarding this question. In line 4 we are creating an object of A. Is it possible to create an object of an interface?
No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete. Still if you try to instantiate an interface, a compile time error will be generated saying “MyInterface is abstract; cannot be instantiated”.
An Interface which looks like a class will contain Abstract methods (body less methods). So we cant create an object to interface but we can create classes where we can implement the abstract methods of the interface.
We cannot create an object of an interface in Java. Interfaces in java can be defined as a full abstract class with fields (public , static & final) and empty methods (public and abstract).
Interface is basically a complete abstract class. That means Interface only have deceleration of method not their implementation. So if we don't have any implementation of a method then that means if we create object of that interface and call that method it compile nothing as there is no code to compile.
What you are seeing here is an anonymous inner class:
Given the following interface:
interface Inter { public String getString(); }
You can create something like an instance of it like so:
Inter instance = new Inter() { @Override public String getString() { return "HI"; } };
Now, you have an instance of the interface you defined. But, you should note that what you have actually done is defined a class that implements the interface and instantiated the class at the same time.
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