What is the syntax for constructors in Java?

In Java, constructors are written as follows:

  1. The constructor has the same name as the class.
  2. Constructors do not have a return type, including void type.
  3. Constructors can either have parameters or not.
  4. If a constructor is not explicitly defined in Java, a default parameterless constructor will be provided. If a constructor is explicitly defined, the default parameterless constructor will no longer be provided.
  5. fresh

Here is an example code for the constructor:

public class MyClass {
    private int myField;

    // 无参构造器
    public MyClass() {
        // 初始化字段
        myField = 0;
    }

    // 带参数的构造器
    public MyClass(int value) {
        // 初始化字段
        myField = value;
    }

    // 其他方法
    public int getMyField() {
        return myField;
    }

    public void setMyField(int value) {
        myField = value;
    }

    public static void main(String[] args) {
        // 使用无参构造器创建对象
        MyClass obj1 = new MyClass();
        System.out.println(obj1.getMyField());  // 输出:0

        // 使用带参数的构造器创建对象
        MyClass obj2 = new MyClass(10);
        System.out.println(obj2.getMyField());  // 输出:10
    }
}

In the code provided above, the class MyClass has a private field called myField, and it includes a constructor with no parameters as well as a constructor with parameters. In the main method, two objects are created using these two constructors, and the initialization of the field is then verified.

bannerAds