Why does running TestClass.main () output 202 202 101?
class BaseClass
{
int data = 101;
public void print()
{
System.out.print(data + " ");
}
public void fun()
{
print();
}
}
class SubClass extends BaseClass
{
int data = 202;
public void print()
{
System.out.print(data + " ");
}
}
class TestClass
{
public static void main(String[] args)
{
BaseClass obj = new SubClass();
obj.print();
obj.fun();
System.out.print(obj.data);
}
}
With my poor knowledge of OOP, I believe that execution should be like this:
1- obj.print (); fingerprints 202 from SubClass
2- Since obj.fun () does not exist; method in the subclass it calls the parent method, so the output should be 101
3- System.out.print (obj.data); should print 202 because the value is overridden in a subclass.
So, I think that the output will be 202 101 202, but this is not so, can you explain to me why?
source
share