Hello everyone, This is from jtips.net, mock exam no. 1
The output is: sub.methodA() = 1 sup.methodA() = 0 sup1.methodA() = 10 I don't understand why process(sup1) leads to an output of zero. sup1 is an object of Subclass, and x in Subclass is 1! I am obviously confused about the rules about upcasting. Can you help me?
Let me try to explain. When you pass sup1 to the function process(Superclass obj), it is actually a Superclass reference pointing to a Subclas object. The value of variable x is picked up on the basis of reference type(Superclass) and not on the what the reference is actually pointing to (sup1). Hence the value returned is value of x in Superclass i.e. 0. bye