I am going through my notes(after 5-6 months) and I am unable to understand the output given by following code :
class Base
{
int x=20;
}
class Child extends Base
{
int x=50;
public static void main(String arg[])
{
Base b = new Child(); //upcasting
System.out.println(b.x); // prints 20
}
}
I expected the output to be 50 but the output is 20. I don't understand reason behind this output.
I know int x = 20 in Base is same as Child class's int x = 50 resulting in data hiding . Also reference id of Child class is in Base class reference variable b resulting in upcasting .
Both of these should result in 50 as output , since b is having refernce id of the child class so b.x should be 50 and also because by data hiding int x= 50 hides int x = 20 .
So, why output is 50.