atg atg - 4 months ago 8
Java Question

Initializing New Class With Inheritance

Can someone explain the differences between these three declarations.

Animal var = new Dog()


Dog var = new Dog()


Dog var = new Animal()


The second declaration is most used, but I don't understand what role the left class has vs the right class, or when you use one vs the other.

The assumption is Dog extends Animal.

Answer

Animal var = new Dog()

The "type on the right" (Dog) is the actual type of the instance being created. It must be a real class (not an interface). This class defines the "real, implemented behavior" of the new object.

The "type on the left" (Animal) is the type of the variable being used to store the reference to the instance being created. The "type on the left" must be an ancestor class/interface of the "class on the right". Using this variable (without casts), you will only have access to the properties/methods of Animal, and no access to additional properties/methods of Dog (if any). And you may assume that the contract of Animal is implemented, without knowing any of the details, which you would know if the "type on the left" were Dog.

This is very basic polymorphism, please read a tutorial/book on this to get more insight.

Dog var = new Dog()

This is obvious, you operate with an instance of Dog through a variable of type Dog. It's what you surely expect it to be.

Dog var = new Animal()

That's a wrong construct. It'll be a compilation error.