What are the differences in creation of objects in mentioned ways? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What are the differences in creation of objects in mentioned ways?

Say we have an dog class that extends animal class , so What are the differences between , Animal jimmy = new dog(); and Animal jimmy = new Animal(); and Dog jimmy = new Dog(); ?

6th Apr 2021, 6:02 AM
Mons Joseph
Mons Joseph - avatar
2 Answers
+ 3
Assuming Animal is superclass and Dog is its subclass - Let's talk about Animal jimmy = new Dog(); first. Here you are referencing a sub class object to a superclass variable. This is polymorphism in action. This is also known as widening(in reference terms). Using this approach, you can only access methods and variables present in the super (Animal) class because they are not defined in the subclass (Dog). Dog jimmy = new Dog(); is referencing using subclass reference. Here you have access to all methods and variables present in super class as well as sub classes. So using this object, you can access methods and variables of both Animal class and Dog class.
6th Apr 2021, 6:44 AM
Soumik
Soumik - avatar
+ 3
Just to add on to Soumik answer if your using a super type variable to refer to one of its sub type objects and data in sub class hasn't overridden methods of it's super class then during runtime methods will be called on the variable type, if methods are overridden in subclass then during runtime methods will be called on the object type even though the object is being referenced by it's super type this is what polymophisim is all about. :)
6th Apr 2021, 9:02 AM
D_Stark
D_Stark - avatar