Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiating interfaces in Java

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?

like image 725
user1535147 Avatar asked May 25 '13 14:05

user1535147


People also ask

How do you instantiate an interface in Java?

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

Can you instantiate interfaces?

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.

Why can't we instantiate an interface in Java?

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 an instantiate in Java?

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.


1 Answers

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

like image 174
zw324 Avatar answered Oct 13 '22 12:10

zw324