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