The initialization steps for Java objects are as follows:
1. First initialize the storage space allocated to the object to binary 0;
2. If there is an inheritance, the constructor of the base class is called first;
3. Invoke the initialization method of the member in the order in which it is declared;
4. Call the constructor principal of the exported class.
Look at the following example:
classglyph{voidDraw () {System.out.println ("Glyph.draw ()"); } Glyph () {System.out.println ("Glyph () before Draw ()"); Draw (); System.out.println ("Glyph () after draw ()"); }}classRoundglyphextendsglyph{Private intRADIUS = 1; Roundglyph (intr) {radius=R; System.out.println ("Roundglyph.roundglyph (). Radius =" +radius); } voidDraw () {System.out.println ("Roundglyph.draw (). Radius =" +radius); }} Public classpolyconstructors{ Public Static voidMain (string[] args) {NewRoundglyph (5); }}
Output Result:
Results Analysis:
1). The export class Roundglyph overrides the Draw () method in the base class glyph. When the base class glyph constructor calls the draw method, Roundglyph's Draw () method is actually called;
2). Because the object is initialized, the storage space allocated to the object is first initialized to binary 0, so the radius value is 0 at this point.
Conclusion:
1). When writing a constructor, there is a valid guideline: "To get the object into a normal state in as simple a way as possible, and to avoid invoking other methods if possible";
2). The only methods that can be safely called within the constructor are the final methods in the base class (also applicable to private methods, which are automatically part of the final method). These methods cannot be overwritten, so there is no such surprising problem.
Initialization process for Java objects