Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we create an object of an interface?

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?

like image 608
shirsendu shome Avatar asked Oct 22 '10 19:10

shirsendu shome


People also ask

Why we can not create an object of 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”.

Can we create an object for an interface in selenium?

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.

Can we create object for interface in spring?

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).

Why do we create object of interface?

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.


1 Answers

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.

like image 165
jjnguy Avatar answered Sep 28 '22 01:09

jjnguy