Ganish Patil wrote:What is difference between these two object creation of SubClass ?
Nothing. The only difference is the declared type of the variable that stores the reference.
How these objects get created in memory?
Not important. The only thing that's important is what the compiler "knows" about those two variables.
In the case of subObj1, it knows it's a SubClass.
In the case of baseRefSubObj, it knows it's a BaseClass.
So in the latter case, it won't let you call any method that is only defined in SubClass.
The "polymorphic" part is that when you call baseRefSubObj.getMessage() you will get
SubClass: Hello because baseRefSubObj is actually a SubClass object, so it will call SubClass's version of the method.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
sal jefferson wrote:...you will want to declare the object as an Animal.
You don't have to declare a reference as Animal in order to add it into an Animal array. You can declare a reference as a Dog and add it into an Animal array. For example, you can add these references into an Animal array.
A polymorphic reference (a reference that refers to a subtype) is useful only if you need to use it to polymorphically call a method overridden in the subtype. For example, when you do this Animal animals = new Dog(), you can use animals to call a method overridden in Dog. You can later do this animals = new Cat() and still be able to use the same reference to call a method overridden in Cat.
posted 2 years ago
Thanks for the clarification. I have been wrong twice so far today, that I know of. This is good learning for me. I am glad to get these wrong answers out of the way before a test or interview.
My, my, aren't you a big fella. Here, have a tiny ad: