Why is the output different in the two cases?

前端 未结 3 1976
慢半拍i
慢半拍i 2021-01-22 06:10

Why is the output different in the below case even when, the variable has been overridden?

public class A {
    int a = 500;

    void get() {
        System.out         


        
3条回答
  •  长发绾君心
    2021-01-22 06:36

    There is no such thing as overridden variables. B actually has two instance variables named a: one it declares and another it inherits. See this:

    B ob = new B();
    System.out.println("B.a is " + ob.a);
    System.out.println("A.a is " + ((A)ob).a);
    

    Inside a B's instance method you can write super.a or ((A)this).a to access the parent's variable.

提交回复
热议问题