Java 构造方法

构造方法的类型、重载、this 关键字与初始化顺序。

Beginner
Key Points构造方法与类同名、无返回值;不写则编译器送一个无参构造,一旦自定义就没了;this(...) 可调用同类其他构造。

构造方法的类型

Constructors are either no-arg or parameterised. No-arg constructors let frameworks instantiate reflectively; parameterised ones initialise in one step. They cannot be static, final or abstract.

Java
public class Student {
    String name;
    int age;

    public Student() {
        this.name = "unknown";
        this.age = 0;
    }

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

    public static void main(String[] args) {
        Student a = new Student();
        Student b = new Student("Tom", 20);

        System.out.println(a.name + " " + a.age);
        System.out.println(b.name + " " + b.age);
    }
}
Output
unknown 0
Tom 20

构造方法的重载

Several constructors with different parameter lists are overloads. The common pattern has shorter ones delegate to the fullest via this(...), so initialisation logic lives in one place.

Java
public class Box {
    int w;
    int h;
    String label;

    public Box() {
        this(1, 1, "default");
    }

    public Box(int w, int h) {
        this(w, h, "box");
    }

    public Box(int w, int h, String label) {
        this.w = w;
        this.h = h;
        this.label = label;
    }

    public static void main(String[] args) {
        System.out.println(new Box().label);
        System.out.println(new Box(2, 3).label);
        System.out.println(new Box(4, 5, "big").w);
    }
}
Output
default
box
4

构造方法中的 this 关键字

this refers to the current object. It most often disambiguates a parameter shadowing a field: this.name = name. this(...) calls another constructor of the same class and must be the first statement.

Java
public class Employee {
    String name;
    double salary;

    public Employee(String name) {
        this(name, 5000);
    }

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }

    public Employee self() {
        return this;
    }

    public static void main(String[] args) {
        Employee e = new Employee("Tom");
        System.out.println(e.name + " " + e.salary);
        System.out.println(e.self() == e);
    }
}
Output
Tom 5000.0
true
A subclass constructor implicitly starts with super(). If the parent has only parameterised constructors, the subclass must call super(args) explicitly or it will not compile.

Friends & Partners