Instantiating interfaces in Java

user1535147 picture user1535147 · May 25, 2013 · Viewed 58.1k times · Source

I have this interface:

public interface Animal {
    public 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(); //HERE!!!!!!!!!!!!!!!!!!!!!!
        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 "HERE!!!!!!!!!!!!!").

What is happening here?

Answer

zw324 picture zw324 · May 25, 2013

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