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

Gabriel Colón :

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);
    }
}

Harry Coder :

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);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360125&siteId=1