之前学习了编写简单的构造器,可以定义对象的初始状态。但是,由于对象构造非常重要,所以Java提供了多种编写构造器的机制。
有些类有多个构造器。例如,可以如下构造一个空的 StringBuilder
对象:
var messages = new StringBuilder();
或者,可以指定一个初始字符串:
var todoList = new StringBuilder("To do:\n");
此功能称为重载。如果多个方法具有相同的名称和不同的参数,则会发生重载。编译器必须挑选出要调用的方法。它使用每个方法标头中的参数类型来匹配特定方法调用中使用的值类型,以选择正确的方法。如果编译器找不到匹配的参数,则会出现编译时错误,因为根本没有匹配,或者没有比其他参数更好的参数(这种查找匹配的过程称为重载解析)
[En]
This feature is called overloading. If multiple methods have the same name and different parameters, overloading occurs. The compiler must pick out which method to call. It uses the parameter type in the header of each method to match the value type used in a particular method call to select the correct method. If the compiler cannot find a matching parameter, a compile-time error occurs because there is no match at all, or none is better than the others (this process of finding a match is called overloaded parsing)
默认字段初始化
如果在构造器中没有显式地为字段设置初始值,那么就会被自动地赋为默认值:数值为0,布尔值为 false
,对象引用为 null