Why does the execution of TestClass.main() outputs 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 OOP knowledge I think the execution must be this way:
1- obj.print(); prints 202 from SubClass
2- Since there is no obj.fun(); method in Subclass it calls parent method so the output should be 101
3- System.out.print(obj.data); should print 202 since the value is overridden in subclass.
So I think the output would be 202 101 202 but it isn’t, can you explain me why?
Indeed, it calls the super class for
fun, but the super class callsprint, and asprintis overridden, the overriding version (in the subclass) gets called.Variables are not overriden, but hidden by subclass, as
objdeclared asBaseClass, it accesses itdataproperty directly. unlike method call, this is decided at compile time.