Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create an object for Interface?

Is it possible to create an object for an interface? If yes, how is it done? According to my view the following code says that we can:

Runnable r = new Runnable() {
    // some implementation
}
like image 545
kalepu harish Avatar asked Jul 01 '13 09:07

kalepu harish


People also ask

Why we Cannot create an object for interface?

We can't create object of interfaces because of the reason that : Interface is basically a complete abstract class. That means Interface only have deceleration of method not their implementation.

Can we create an object of an interface in Java?

You can create object of an interface through anonymous class while implementing the method of an interface You can declare an object of type interface and create the instance of the class which implements this interface. …………. ……………. Can we create an instance of an interface in Java?

How does the JVM create an object from an interface?

The code you've shown creates an object from an anonymous class, which implements the interface. Under the covers, the JVM actually creates a class implementing the interface, and then creates an instance of that class.

Can you declare an object for an interface?

You can declare an Object for an interface. You cannot instantiate this object directly using this interface. However, let's say you have a class that implements this interface. (This is conceptually of course (like pseudocode) actual code may vary depending on your classes and access modifiers etc.)

What is the difference between an array and an interface in Java?

So, Interfaces in Java are considered to be incomplete and you are not allowed to instantiate (create objects for) it. Whereas, arrays in Java are objects which are dynamically created, and may be assigned to variables of type Object. All methods of class Object may be invoked on an array.


1 Answers

You can create an anonymous inner class:

Runnable r = new Runnable() {
    @Override
    public void run() {
    }
};

Therefore you create a new class which implements the given interface.

like image 83
Uwe Plonus Avatar answered Sep 21 '22 03:09

Uwe Plonus