Java field Initialization

Source: Internet
Author: User

Fields in the Java platform are generally divided into two types: class variables and object variables.

Class 1 variables

Usually modified by static, there are two types of initialization: code blocks and the use of private static methods:

The advantage of the private static method is that it can be reused when you need to reinitialize the variable.

A static initialization code block, like a normal block of code, closed with curly braces {}, preceded by a static keyword, a class can have any number of static initial blocks, and can appear anywhere in the class body. The operating system guarantees that the order of the static initial block calls is consistent with the order in which the source code appears.

Class 2 variables

There are also two types of initialization: Initialize the block final method.

The initialization code block for the instance variable is similar to the static initialization code block, but there is no static keyword.

A final method cannot be overridden by subclasses, which is particularly useful if the subclass is to reuse initialization code, which is set to final, because invoking a non-final method can cause problems when the instance is initialized.

For example:

classinitializeblockclass{{field= 200; }                           //Initialize block     Public intfield = 100;  PublicInitializeblockclass (intvalue) {         This. field =value; }     PublicInitializeblockclass () {}} Public classInitializeblock { Public Static voidMain (string[] args) {Initializeblockclass obj=NewInitializeblockclass ();                System.out.println (Obj.field); Obj=NewInitializeblockclass (300);    System.out.println (Obj.field); }}

The result is:

Java field Initialization

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.