Q:

Why does the object refers to the value of the parent class instead of the class it is assigned to?

Can someone explain why the output is 10 and not 20?
Why does the object refers to the value of the parent class instead of the class it is assigned to?
class A {
    int i = 10;
}

class B extends A {
    int i = 20;
}

public class MainClass {
    public static void main(String[] args) {
        A a = new B();
        System.out.println(a.i);
    }
}

A:

In Java, methods are overridden not variables. So variables belong to their owner classes. a is a reference of type A that point to an object of type B but remains of type A.
To call the i of B, you have to cast a to B.
A a = new B();
System.out.println(((B)a).i);

