[the content of this article is summaried from Thinking In Java]
The process of creating an object.
Consider a class called Dog:
- The first time an object of type Dog is created (the constructor is actually a static method), or the first time a static method or static field of class Dog is accessed, the Java interpreter must locate Dog.class, which it does by searching through the classpath.
- As Dog.class is loaded (creating a Class object, which you’ll learn about later), all of its static initializers are run. Thus, static initialization takes place only once, as the Class object is loaded for the first time.
- When you create a new Dog( ), the construction process for a Dog object first allocates enough storage for a Dog object on the heap.
- This storage is wiped to zero, automatically setting all the primitives in that Dog object to their default values (zero for numbers and the equivalent for boolean and char) and the references to null.
- Any initializations that occur at the point of field definition are executed.
- Constructors are executed. As you shall see in Chapter 6, this might actually involve a fair amount of activity, especially when inheritance is involved.
本文详细介绍了Java中创建对象的过程,包括如何通过构造器初始化对象、静态初始化的时机及作用等。文章还深入探讨了Java解释器如何定位并加载类文件,以及在堆上为对象分配内存的具体细节。


被折叠的 条评论
为什么被折叠?



