Home  >  Article  >  Java  >  What should you pay attention to when using java construction code blocks?

What should you pay attention to when using java construction code blocks?

WBOY
WBOYforward
2023-05-15 09:01:051275browse

1. The concept

appears outside the method in the class. It will be executed every time the constructor is called, and it will be executed before the constructor.

2. Usage Notes

(1) The function of the construction code block is to initialize the object.

(2) The construction code block is run as soon as the object is created, and takes precedence over the constructor function

(3) The difference between the construction code block and the constructor function is: the construction code block is for all objects Unified initialization is performed, and the constructor initializes the corresponding object, because there can be multiple constructors. Whichever constructor is run will create what kind of object, but no matter which object is created, the same construction code block will be executed first. In other words, what is defined in the construction code block is the common initialization content of different objects.

3. Execution sequence

When creating an object, the construction code block will be executed first, and then the constructor function will be executed.

4. Example

package com.initialization;
 
/**
 * 构造代码块的实际使用
 */
public class ConstructBlock {
    public static void main(String[] args) {
        System.out.println("****创建第一个学生****");
        Student stu1=new Student("小明");
        System.out.println();
        System.out.println("****创建第二个学生****");
        Student stu2=new Student(13);
    }
}
 
class Student{
    String area;
    String name;
    int age;
    {
        area="北京";
        System.out.println("所在地区:"+area);
    }
    Student(String name){
        this.name=name;
        System.out.println("姓名:"+this.name);
    }
    Student(int age){
        this.age=age;
        System.out.println("年龄:"+this.age);
    }
}

The above is the detailed content of What should you pay attention to when using java construction code blocks?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete