Initialization process for Java objects

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.