繼承Memory Layout

Prerequisites:

子類別、父類別、祖父類別

1
2
3
4
5
6
7
8
9
class GrandPa {
  String name = "GrandPa";
}
class Father extends GrandPa{
  String name = "Father";
}
class Child extends Father{
  String name = "Child";
}

建立子類別

1
2
3
4
5
public class Test {
  public static void main(String[] args) {
    Child child = new Child();
  }
}

建立步驟

new Child(),發現子類別有父類別,依下方順序載入metadata到記憶體中。

  1. GrandPa Metadata
  2. Father Metadata
  3. Child Metadata

img

建立子類別

  1. 建立子類別記憶體空間
  2. 變數child指向記憶體空間。

img

根據建構子,預設會先呼叫祖父建構子,建立祖父物件。

  1. 先在String Pool中建立GrandPa的文字
  2. name指向String Pool中的記憶體位址。

img

呼叫父類別建構子,建立物件。

  1. 先在String Pool中建立Father的文字
  2. name指向String Pool中的記憶體位址。

img

建立Child物件。

  1. 先在String Pool中建立Child的文字。
  2. name指向String Pool中的記憶體位址。

img

results matching ""

    No results matching ""