Why do we create an object of the Dog class here?
Because the Dog class most likely inherits the Animal class.
then why is this the creation of an object if we have a Dog () is a constructor?
Dog is not a constructor, but a class. But when creating an animal , a constructor from the class Dog .
Why else to say the class is the object?
Because classes describe objects.
Animal animal = new Dog(); - creates a reference to the Dog class of type Animal . Ie, just like a primitive variable is an int type, an animal an Animal type (but it still refers to Dog ).
What is it for? I will give an example. You have three classes: Animal , Dog , Hourse .
class Animal{ int speed; boolean live; String name; public void speedUp() {speed++;} } class Dog() extends Animal{ public Dog(int speed, boolean live, String name) { super.speed = speed; super.name = name; super.live = live; } } class Hourse() { public Hourse(int speed, boolean live, String name) { super.speed = speed; super.name = name; super.live = live; } }
You do not need to rewrite all the variables and methods that Animal in the class Hourse and Dog .
Suppose you have a list of animals (let it be called a pen, from English - a pen). And you need to put in the corral of all animals, and dogs, and cows, and horses. Then you simply declare the list. ArrayList<Animal> pen = new ArrayList<>(); , and you can put all animals there (in our case animal , although it would be more correct to call the variable Dog . But not one dog object, but hourse1 , hourse2 , dog10 , their classes inherit the Animal class).
Example with code:
ArrayList<Animal> pen = new ArrayList<>(); Animal hourse1 = new Hourse(0, true, "1"); Animal hourseBlack = new Hourse(); //не указываю параметры Animal hoursePink = new Hourse(); Animal bigDog = new Dog(); pen.add(hourse1); pen.add(hourseBlack); pen.add(hoursePink); pen.add(bigDog);
This is only one advantage of using polymorphism. Another, as I already wrote in the article, is reuseability of the code, when you can prescribe the same behavior for the heirs ( Dog , Hourse ) in the same class ( Animal ). So you can do it like this: hourse1.speedUp(); bigDog.speedUp(); .