Note:
1. The static initialization occurs only if it's necessary.
2. The static variables will only be initialized when the first static access occurs, and only be initialized once.
3. The order of initialization is statics first, if they haven't already been initialized by a previous object creation, and then the non-static objects.
To summarize the process of creating an object, consider a class called Dog:
1. Even though it doesn't explicitly use the static keyword, the constructor is actually a static method. So the first time an object of type Dog is created, 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.
2. As Dog.class is loaded(creating a Class object), all of its static initializers are run. Thus, static initialization takes place only once, as the class object is loaded for the the first time.
3. When you create a new Dog(), the construction process for a Dog object first allocates enough storage for a Dog object on the heap.
4. This storage is wiped to zero, automatically setting all the primitive in that Dog object to their default values(zero for numbers and the equivalent for boolean and char) and the references to null.
5. Any initializations that occur at the point of field definition are executed.
6. Constructors are executed.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment