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

20th Jan 2017, 2:50 PM
vairavan Somasundaram
vairavan Somasundaram - avatar
4 Respuestas
+ 10
"new" triggers the constructor of the class and is necessary…… (creates an instance of the class (object))
20th Jan 2017, 2:56 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 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.
20th Jan 2017, 3:11 PM
Robobrine
Robobrine - avatar
+ 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.
30th Jan 2017, 5:16 PM
Israel
Israel - avatar
0
thanks a lot for your help
20th Jan 2017, 3:33 PM
vairavan Somasundaram
vairavan Somasundaram - avatar