要创建一个_类_的实例,需要通过new运算符调用它的构造器。
构造器是一种特殊的方法,它的作用是初始化刚刚创建的实例。
构造器看起来和普通方法一样,但没有返回类型,而且名字与类名相同。
class Library {
private int books;
public Library() {
this.books = 10;
}
}
// This will call the constructor
var library = new Library();
和普通方法一样,构造器也可以有形参。 构造器的形参通常会保存为(私有的)字段,以便之后访问,或者用于某种一次性的计算。 实参可以像传给普通方法那样传给构造器。
class Building {
private int numberOfStories;
private int totalHeight;
public Building(int numberOfStories, double storyHeight) {
this.numberOfStories = numberOfStories;
this.totalHeight = numberOfStories * storyHeight;
}
}
// Call a constructor with two arguments
var largeBuilding = new Building(55, 6.2)
构造器不是必须指定的。 如果没有指定构造器,编译器会生成一个无参构造器:
class Elevator {
}
// This will call the (empty) generated constructor
var elevator = new Elevator();
如果字段被赋了初始值,编译器生成的代码会把这个赋值实际放进构造器里。 因此,下面这两个类声明在功能上是等价的:
class UsingFieldInitialization {
private int players = 5;
}
class UsingConstructorInitialization {
private int players;
public UsingConstructorInitialization() {
players = 5;
}
}