Initialization program block for Java

Source: Internet
Author: User

Initialization blocks: Initialization of the execution sequence during class instantiation is the execution of the static initialization block, then the normal initialization block, the last execution of the constructor, and the static initialization only for the first time
Executed and executed only once when instantiated.
public class HelloWorld {

String name; Declaring variable name
String sex; Declaring variables Sex
static int age;//declares a statically variable age

Construction method
Public HelloWorld () {
SYSTEM.OUT.PRINTLN ("Initialize name by construction method");
Name = "Tom";
}

Initialize block
{
SYSTEM.OUT.PRINTLN ("Initialize sex by ordinary initialization block");
Sex = "male";
}

Static initialization blocks
static {
SYSTEM.OUT.PRINTLN ("Initialize age by static initialization block");
Age = 20;
}

public void Show () {
System.out.println ("Name:" + name + ", Gender:" + Sex + ", Age:" + ages ");
}

public static void Main (string[] args) {

Creating objects
HelloWorld Hello = new HelloWorld ();
Call the Show method of an object
Hello.show ();
HelloWorld hello1=new HelloWorld ();
Hello1.show ();
}
}
Execution Result:
Initializing the age with static initialization blocks
Initialize sex with normal initialization blocks
Initialize name by constructing method
Name: Tom, Sex: Male, Age: 20
Initialize sex with normal initialization blocks
Initialize name by constructing method
Name: Tom, Sex: Male, Age: 20

Initialization program block for Java

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.