Java-4.7 constructor initialization (3)

Source: Internet
Author: User

Java-4.7 constructor initialization (3)

Next, go to the previous chapter.

(4) initialize static explicit Fields

Some attribute fields are initialized using static code blocks.

package com.ray.testobject;public class Test {private static int id;private static String name;static {id = 0;name = abc;System.out.println(id: + id);System.out.println(name: + name);}public static int getId() {return id;}public static void main(String[] args) {// new Test();System.out.println(Test.getId());}}

 

If we release new Test (), the following results will be obtained. Because the code block is executed only once.


Output:

Id: 0
Name: abc
0

 

Here is an example:

package com.ray.testobject;public class Test {private static int id = 0;private static String name;static {System.out.println(id: + id);name = abc;System.out.println(name: + name);}public Test() {System.out.println(create Test);}public static void main(String[] args) {new Test();new Test();}}


Output:

Id: 0
Name: abc
Create Test
Create Test

 

(5) initialize non-static Domains

package com.ray.testobject;public class Test {private String name;{name = abc;System.out.println(name: + name);}public static void main(String[] args) {new Test();new Test();}}


Output:

Name: abc
Name: abc

Initialize non-static fields. Each new code block is executed once.

 

Summary: This chapter mainly discusses explicit static domain initialization and non-static domain initialization.

 

This chapter is here. Thank you.

-----------------------------------

 

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.