Java construction method (constructor)

Table of contents

1. What is a construction method?

2. The use of construction methods


1. What is a construction method?

Construction method (also known as constructor constructor ) : It is a special member method whose name must be the same as the class name . When an object is created, it is automatically called by the compiler , and it is called only once during the entire life cycle of the object .

2. The use of construction methods

The name of the construction method is the same as the class name, and there is no return value type. Generally, public modification is used, and the construction method can be overloaded (customize the construction method with different parameters according to your own needs)

The syntax of the constructor

 [ modification list ] construction method name ( formal parameter list ) {

        constructor method body;

}

When no constructor is customized, the compiler will automatically provide a parameterless constructor

public class Student {
    private String name;
    private int age;
    private double score;
}

At this point, the compiler will provide a no-argument constructor for the Student class

   public Student(){
        
    }

Once a constructor is defined, the compiler no longer provides a constructor

public class Student {
    private String name;
    private int age;
    private double score;

    //带有三个参数的构造方法
    public Student(String name, int age, double score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }
}

Create an object without parameters at this time, and the compiler reports an error 

 Therefore, it is recommended that when creating a constructor, always add a parameterless constructor

IDEA can quickly generate construction methods, right mouse button or alt+Insert

 

 In the constructor, you can simplify the code by using this to call other constructors

public class Student {
    private String name;
    private int age;
    private double score;
    
    public Student(){
        this("张三",20,60);
    }

    public Student(String name, int age, double score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }
}

Note:

this() must be the first statement in the constructor

 

and cannot call each other

 

Guess you like

Origin blog.csdn.net/2301_76161469/article/details/132050483