I have this interface:
public interface Animal { void Eat(String name); }
And this code here implements the interface:
public class Dog implements Animal { public void Eat(String food_name) { System.out.printf(food_name); } public static void main(String args[]) { Animal baby2 = new Dog(); // <- this line baby2.Eat("Meat"); } }
My question is, why does the code work? An interface cannot be instantiated. Yet in this case, interface was instantiated (marked with the comment).
What is happening here?
Java For Testers 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 can't be instantiated directly. Its members are implemented by any class or struct that implements the interface. A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.
You can't instantiate an interface or an abstract class because it would defy the object oriented model. Interfaces represent contracts - the promise that the implementer of an interface will be able to do all these things, fulfill the contract.
What is instantiation in Java? In Java, an OOP language, the object that is instantiated from a class is, confusingly enough, called a class instead of an object. In other words, using Java, a class is instantiated to create a specific class that is also an executable file that can run on a computer.
No it is not - you are instantiating a Dog
, but since a Dog
is an Animal
, you can declare the variable to be an Animal
. If you try to instantiate the interface Animal
it would be:
Animal baby2 = new Animal();
Try that, and watch the compiler scream in horror :)
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