Memory allocation is done before first line of constructor execution or after constructor execution – Java

huangapple go评论82阅读模式
英文:

Memory allocation is done before first line of constructor execution or after constructor execution - Java

问题

在上面的代码中,我们创建了一个名为Student的类对象,在这个对象中,JVM是在构造函数的第一行执行之前分配内存还是在构造函数执行之后分配内存,甚至在父类之后分配内存?

英文:
Student student = new Student();

In the above code, we have created one Student class object, in that is JVM allocate the memory before the first line of constructor execution or after the constructor execution, Even after the parent classes?

答案1

得分: 1

当声明一个类类型的变量时,只创建一个引用。只有当使用new()关键字初始化该变量时,才会分配内存(在堆上)。如果您使用NetBeans,可以使用NetBeans分析器来检查内存读/写操作,虽然我猜想大多数IDE都包含类似的工具。内存分配是在构造函数内部的第一件事,而不是最后。

英文:

When a variable of class type is declared only a reference is created. Memory is allocated (in the heap) only when said variable is initialized with the new() keyword. You should be able to check the memory read/write operations with NetBeans profiler if you're using Netbeans, though I guess most IDE include a similar tool.
The memory is allocated as first thing inside the constructor rather than last.

答案2

得分: 0

In short, it is allocated before the constructor.

Your code can be also written like this:

Student student;
student = new Student();

This means that when the variable student is declared, it is declared as an empty reference in the first line. When that happens, the memory allocated a space for student, declaring it as a variable of type Student as a reference until initialized into a usable variable.

英文:

In short, it is allocated before the constructor.

Your code can be also written like this:

Student student;
student = new Student();

This means that when the variable student is declared, it is declared as an empty reference in the first line. When that happens, the memory allocated a space for student, declaring it as a variable of type Student as a reference until initialized into a usable variable.

huangapple
  • 本文由 发表于 2020年7月22日 23:46:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63038179.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定