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

后端 未结 10 1659
我寻月下人不归
我寻月下人不归 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:48

    When you compile your code it pretty much becomes like:

    class A extends java.lang.Object
    {
        int a=2,b=3;
        public void display()
        {
            int c=a+b;
            System.out.println(c);
        }
    }
    class B extends A
    {
        int a = 5, b = 6;
        public void display()
        {
          super(); //When you call y.display() then this statement executes.
        }
    }
    class Tester
    {
        public static void main(String arr[])
        {
            A x = new A();
            B y = new B();
            x.display();
            y.display();
        }
    }
    

    And hence, when super calls, the method of class A is being called.

    Now go to method of class A. Here int c = a + b; means c = this.a + this.b; which is 2 + 3.

    And the result is 5.

提交回复
热议问题