How does inheritance of instance fields work in this particular code?

后端 未结 10 1671
我寻月下人不归
我寻月下人不归 2020-12-24 11:11
class A
{
    int a = 2, b = 3;
    public void display()
    {
        int c = a + b;
        System.out.println(c);
    }
}
class B extends A
{
    int a = 5, b =          


        
10条回答
  •  一向
    一向 (楼主)
    2020-12-24 11:50

    Why does the output come out as 5,5? And not 5,11?

    Whenever we have same instance variables (applicable to class variable as well) in a class hierarchy, the nearest declaration of the variable get the precedence. And in this case, nearest declaration of a and b from display () method is A’s. So class B’s instance variables go hidden. Hence in both cases, 5 gets printed.

    How would the y.display() method work?

    Another alternative is to have getter in both classes to get value of a and b.

        class A
    {
        int a = 2, b = 3;
        public int getA() {
            return a;
        }
    
        public int getB() {
            return b;
        }
        public void display()
        {
            int c = getA() + getB();
            System.out.println(c);
        }
    }
    class B extends A
    {
        int a = 5, b = 6;
        public int getA() {
            return a;
        }
    
        public int getB() {
            return b;
        }
    }
    class Tester
    {
        public static void main(String arr[])
        {
            A x = new A();
            B y = new B();
            x.display();
            y.display();
        }
    }
    

    Prints

    • 5
    • 11

提交回复
热议问题