- A class is loaded.
- A class is created/instantiated.
JVM does the following when it encounters class instantiation,
- Allocates memory space for a new object, with room for the instance variables.
- Process the constructor. If the constructor has parameters, JVM creates variables for the parameters and assigns them values passed in.
- If the invoked constructor begins with a call to another constructor by using "this" keyword, JVM processes the called constructor.
- Initialize instance and instance variable for this class. Undefined instance variables will be assigned default values.
- Executes the rest of the invoked constructor.
- Returns a reference variable that refers to the newly created object
Note:
- Static initialization is performed first before any instantiation takes place, even if the code comes later in the program.
EXAMPLE
package mypackage; public class MyClass { int x = 3; int y; // instance initialization code block { y = x*2; System.out.println (y); } // static initialization code happens first static { System.out.println ("Static initialization, this will come first."); } public static void main (String[] args) { MyClass inst0 = new MyClass(); MyClass inst1 = new MyClass(); } }
The instance initialization code can go unnoticed when the code gets bigger. A better practice to write initialization code is to put it in the constructor so it's more noticeable.
package mypackage; public class MyClass2 { int x = 3; int y; // instance initialization code in the constructor public MyClass2 () { y = x*2; System.out.println (y); } // static initialization code happens first static { System.out.println ("Static initialization, this will come first."); } public static void main (String[] args) { MyClass2 inst0 = new MyClass2(); MyClass2 inst1 = new MyClass2(); } }
If you have more than one constructor and each calls the same block of code, wrap the common initialization code in a method and let the constructors call it.
package mypackage; public class MyClass3 { int x = 3; int y; // Two constructors public MyClass3 () { init(); } public MyClass3 (int x) { this.x = x; init(); } // instance initialization code in a method private void init () { y = x*2; System.out.println (y); } // static initialization code happens first static { System.out.println ("Static initialization, this will come first."); } public static void main (String[] args) { MyClass3 inst0 = new MyClass3(); MyClass3 inst1 = new MyClass3(); } }
In C++, you must destroy objects after use. Java comes with a garbage collector which destroys unused objects and frees memory space.
No comments:
Post a Comment