在Java中创建对象时会发生什么? [英] What occurs when object is created in Java?
问题描述
我的老师给了我一个问题:
My teacher gave me a question:
用Java创建对象时会发生什么。
"What occurs when objects are created in Java".
据我所知,在创建对象时会发生内存分配,变量初始化和构造函数方法调用。
To the best of my knowledge, memory allocation, variable initialization and constructor method invocation happen when an object is created.
但我的老师说我几乎是对的。除了内存堆之外,后来的两件事情是正确的。相反,他说内存分配发生了。我认为该对象存储在堆中,所以我的老师错了。你这么认为吗?
But my teacher said that I was almost right. The 2 later things are right, except memory heap. Instead, he said the memory allocation occurs. I think that object is stored in heap, so my teacher is wrong. Do you think so?
推荐答案
与往常一样,找到这类问题的解决方案的最佳位置是Java语言规范。
As always, the best place to find a solution for these kinds of questions is in the Java Language Specification.
具体来说,来自关于新实例创建的部分,可以理解这是创建新对象时的顺序,只要没有异常发生:
Specifically, from the section on new instance creation, it can be understood that this is the sequence when a new object is created, as long as no exceptions occur:
- 已分配内存。
- 字段初始化为默认值。
- 的第一行选择的构造函数被调用,除非它是
Object
。第一行我指的是调用super()
或this()
,或隐式调用super()
。 - 实例初始化程序被执行,字段初始化为其请求的值(实际上字段初始化通常编译为实例初始化程序的内联部分)。
- 执行其余的构造函数代码。
- Memory is allocated.
- Fields are initialized to their default values.
- The "first line" of the chosen constructor is invoked, unless it's an
Object
. By first line I mean either explicit call tosuper()
orthis()
, or an implicit call tosuper()
. - The instance initializer is executed and the fields are initialized to their requested values (actually field initialization is usually compiled as an inline part of the instance initializer).
- The rest of the constructor code is executed.
现在,您的老师可能正在谈论内存分配作为一个实际的操作系统调用 - 在这种情况下,他是正确的,因为JVM管理自己的堆,因此Java内存分配不一定转换为操作系统内存分配电话(尽管可能)。
Now, it is possible that your teacher is talking about memory allocation as an actual operating system call - and in that case he's right in the sense that the JVM manages its own heap and thus a Java memory allocation does not necessarily translate to an OS memory allocation call (although it may).
这篇关于在Java中创建对象时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!