Why is the output different in the two cases?

假如想象 提交于 2019-12-02 01:59:44

问题


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.println("a is " + this.a);
    }
}

public class B extends A {
    int a = 144;
}

public class mainmethod {
    public static void main(String args[]) {
        B ob = new B();
        System.out.println("a is " + ob.a);
        ob.get();
    }
}

回答1:


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.




回答2:


When doing ob.a, you get the variable int a from your ob object, which is object of the class B.

However, when you do ob.get();, you are calling the get()-method from class A, because there is no get() in B, which - as you wrote - uses this.a, which would be the int a of class A in that case.




回答3:


No the variable is not overridden. ob.a print the a variable of B class. ob.get() searches for the get method in B class.when it does not gets there it then searches the parent class and executes it.



来源:https://stackoverflow.com/questions/32350894/why-is-the-output-different-in-the-two-cases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!