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(); ?
2 odpowiedzi
+ 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.
+ 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. :)