简体   繁体   中英

How memory allocates to superclass and subclass members when we create object of subclass using superclass reference variable

class A {
    int y = 10;

    void m1() {
        System.out.println("This is M1");
        int b = 20;
    }
}

public class B extends A {

    int x = 10;
    int y = 20;

    void m1() {
        System.out.println("This is M2");
    }

    public static void main(String[] args) {
        A a = new B();
        System.out.println(a.y);
        a.m1();
    }

}

What will be the memory allocation chart/diagram for this?

  • new B :
    • B is allocated, size of B (includes size of A) all field defaulted
    • constructor of B() :
      • super.A() called; recurses:
        • constructor of A() :
        • super.Object() called; recurses
        • all initialized fields of A are assigned: A.this.y = 10;
        • rest of the A constructor statements is executed
      • all initialized fields of B are assigned: B.this.x = 10; B.this.y = 20; B.this.x = 10; B.this.y = 20;
      • rest of the B constructor statements is executed

So the allocation is primarily done in the new .

The allocation done in the constructor and field initialisations can be illustrated in the next corner cast (to be avoided):

class A {
    A() {
        init(); // VERY BAD STYLE
    }
    protected void init() {
    }
}

class B extends A {
    String s1 = null;
    String s2;
    String s3 = "s3";
    String s4;
    String s5 = "s5";
    B() {
        // s1: null, s2: null, s3: null, s4: null, s5: null
        // super() called, calling init()
        // s1: "i1", s2: "i2", s3: "i3", s4: null, s5: null
        // field initialisation:
        // - s1 = null; s3 = "s3"; s5 = "s5";
        // s1: null, s2: "i2", s3: "i3", s4: null, s5: "s5"
        // remaining code of constructor
    }

    @Override
    protected void init() {
        // s1: null, s2: null, s3: null, s4: null, s5: null
        s1 = "i1";
        s2 = "i2";
        s3 = "i3";
        // s1: "i1", s2: "i2", s3: "i3", s4: null, s5: null
    }
}

The above shows the starting life times of fields, and the unexpected moments if someone ever uses overridable methods in a constructor .

It also shows that in the constructor of A the super fields already exist (with default values null, 0, false, 0.0, ... ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM