0

Difference between the 2 syntaxes

What is the difference between Animal v=new Animal(); and Animal v=new Dog(); in Java? Pls explain with examples. Thanx in advance.

24th Aug 2021, 8:03 AM
Santosh Pattnaik
Santosh Pattnaik - avatar
10 Antworten
+ 1
If Animal v=new Dog() is written then it will use the overrided method of Animal class and will implement method of dog class. This process is called dynamic method dispatch And in Animal v=new Animal () only the method of Animal class will be implemented
24th Aug 2021, 3:59 PM
Atul [Inactive]
+ 1
Eagle E if I write Dog v = new Dog() instead of Animal v=new Dog() what are the circumstances of being a bad code or there is no such thing, just depends on personal preference?
24th Aug 2021, 12:33 PM
Santosh Pattnaik
Santosh Pattnaik - avatar
24th Aug 2021, 4:15 PM
Atul [Inactive]
+ 1
Atul [Inactive] When I use At v=new At() the output is same. What are the purpose of this and the code u provided, that is where should I use what because both produce same output
24th Aug 2021, 4:44 PM
Santosh Pattnaik
Santosh Pattnaik - avatar
+ 1
Because when you create an object it's default constructor is always executed. So the first output will be same. The thing to consider is the 2nd output
24th Aug 2021, 5:06 PM
Atul [Inactive]
0
You should redo the tutorial. The reason one would assign a Dog object to an Animal object is to be able to also add other types of animal objects to your program but still use them all through one type: the parent class of animals, Animal. A typical example would be when you have a list of Animal type. You add objects to it that are subclasses of Animal (e.g. Dog, Cat, Lion, Zebra, ...). Then say that you want to know what type the third animal in the list is: animal_list[2].animal_type().
24th Aug 2021, 10:12 AM
Eagle E
Eagle E - avatar
0
Atul [Inactive] which method you are inferring the constructor method or class methods?
24th Aug 2021, 4:04 PM
Santosh Pattnaik
Santosh Pattnaik - avatar
0
Eagle E Atul [Inactive] i noticed that the constructor of both animal and dog is called when i do both Animal v=new Dog() and Dog v=new Dog() But i cannot call any method of dog when in Animal v=new Dog() but could call any method of animal and dog both when Dog v=new Dog()
26th Aug 2021, 7:18 AM
Santosh Pattnaik
Santosh Pattnaik - avatar
26th Aug 2021, 7:33 AM
Atul [Inactive]
0
Atul [Inactive] that occurs in inheritance that was out of the topic of my question Thanku for solving my doubts
29th Aug 2021, 5:48 AM
Santosh Pattnaik
Santosh Pattnaik - avatar