Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-05-15 09:01:05
forward
1371 people have browsed it

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);
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template