class Base
{
int i = 99;
public void amethod()
{
System.out.println("Base.amethod()");
}
Base()
{
amethod();
}
}
public class Derived extends Base
{
int i = -1;
public static void main(String argv[])
{
Base b = new Derived();
System.out.println(b.i);
b.amethod();
}
public void amethod()
{
System.out.println("Derived.amethod()");
}
}
Why does this code print b.i = 99 and not b.i = -1?
Thank you.
It’s because you are referencing a member variable of the object instead of a method. Since it is declared as a Base object, it will use Base.i because member variables do not benefit from polymorphism that is afforded to methods. If you added a getI() method to both classes and called that instead of just b.i, it would work as you expect.