[英]Amount of Memory allocation for Creating Object based on Class Size
計算機如何知道為一個 object 分配多少 memory(根據不同大小的班級)? 下面是一個例子。
public class Point(){
public int x;
public int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
Point x = new Point();
new關鍵字先為新的object分配memory,然后調用class的構造函數,在調用構造函數之前,計算機如何知道為新創建的object分配多少memory?
JVM 知道是因為它已經讀取了描述 class 的.class
文件。
如果運行命令javap -v Point.class
,您可以自己看到:
...
class Point
minor version: 0
major version: 58
flags: (0x0020) ACC_SUPER
this_class: #1 // Point
super_class: #3 // java/lang/Object
interfaces: 0, fields: 2, methods: 1, attributes: 1
...
{
public int x;
descriptor: I
flags: (0x0001) ACC_PUBLIC
public int y;
descriptor: I
flags: (0x0001) ACC_PUBLIC
...
因為它知道有兩個字段,都是int
( descriptor: I
) 類型,所以它確切地知道需要多少 memory。
試圖寫評論,但它太長了。
這一行:
Point x = new Point();
可以分為三個部分:
Point x
=
new Point()
第 3 部分(對象實例化)導致 memory 分配和實例初始化。 只有第 3 部分定義了您要分配的 object( new Point()
、 new Circle()
等)。 由於運行時知道類型,它可以計算所需的 memory 的數量。
第1部分(變量聲明)只是告訴代碼rest,它如何訪問新分配的object,所以,賦值運算符=
從左到右的類型可能不同。
如果Point
和Circle
都會繼承同一個基數 class Drawing
,那么在 C# 中可以這樣寫:
Drawing x = new Point();
此示例仍然分配點,因為new Point()
,但代碼 rest 只能將點用作基礎 class 實例, Drawing
,例如:
x.Draw();
並且不能將其用作Point
而不進行轉換:
x.x = 100; // compile time error
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.