[英]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.