Rules for initializing Java fields

Source: Internet
Author: User

1. Sample program:

1 classInitializeblockclass2 {3     {4field=200;5     }6      Public intfield=100;7      PublicInitializeblockclass (intvalue) {8          This. field=value;9     }Ten      PublicInitializeblockclass () { One          A     } - } -  the  Public classInitializeblockdemo { -      Public Static voidMain (string[] args) { -          -Initializeblockclass obj=NewInitializeblockclass (); + System.out.println (Obj.field); -          +obj=NewInitializeblockclass (300); A System.out.println (Obj.field); at     } -  -}

2. Running Results

3. Results Analysis

(1)

{

field=200;

}

This section is the initialization block for the class, and you can enclose the statement in the class using "{" and "}", directly as a member of the class. This "No Name" member of the class is used to initialize the fields of the class.

(2)

public int field=100; Initialize when defined , at this time field = +;

(3)

System.out.println (Obj.field); Output field value of

(4)

Obj=new Initializeblockclass (300);

System.out.println (Obj.field);

Using the constructor method to initialize , The value of field is initialized to

the rule of initialization of the 4.Java field .

(1) The default value specified when executing the class member definition or the initialization block of the class, exactly which one you want to see is "in front".

(2) executes the constructor of the class.

Note: The initialization blocks of the class do not receive any parameters, and they are executed whenever an object of the class is created. Therefore, it is appropriate to encapsulate those "code that must be executed when the object is created."

Rules for initializing Java fields

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.