0
What is the use of the line "Animal dog =new animal();". Why can't we use directly "Animal dog; dog.bark;"what's the role of new
4 ответов
+ 10
"new" triggers the constructor of the class and is necessary…… (creates an instance of the class (object))
+ 1
If you had a class 'Dog' that extends Animal you could write Animal dog = new Dog();
So it's important to tell Java what class you want to use to create the object.
+ 1
In the statement Animal dog = new Animal();
The first part - Animal dog - is just an empty variable named dog of type Animal, but it does not contain any object until the new keyword and the constructor of the desired class type is used as in
= new Animal();
After that it will actually "contain" an object and you will be able to use the object properties and methods.
0
thanks a lot for your help