Java默认构造函数
构造函数的“默认”是它们没有任何参数。
如果我们没有指定任何构造函数,编译器将为我们生成一个默认构造函数。
这意味着以下两个片段在语义上是等效的:
public class TestClass {
private String test;
}
public class TestClass {
private String test;
public TestClass() {
}
}
默认构造函数的可见性与类的可见性相同。
因此,包私有定义的类具有包私有默认构造函数
但是,如果我们有非默认构造函数,编译器将不会为我们生成默认构造函数。
所以这些不是等价的:
public class TestClass {
private String test;
public TestClass(String arg) {
}
}
public class TestClass {
private String test;
public TestClass() {
}
public TestClass(String arg) {
}
}
请注意,生成的构造函数不执行非标准初始化。
这意味着类的所有字段都将具有其默认值,除非它们具有初始值设定项。
public class TestClass {
private String testData;
public TestClass() {
testData = "Test"
}
}
构造函数是这样调用的:
TestClass testClass = new TestClass();
带参数的构造函数
可以使用任何类型的参数创建构造函数。
public class TestClass {
private String testData;
public TestClass(String testData) {
this.testData = testData;
}
}
像这样调用:
TestClass testClass = new TestClass("测试数据");
一个类可以有多个具有不同签名的构造函数。
要链接构造函数调用(实例化时调用同一类的不同构造函数),请使用 this()。
public class TestClass {
private String testData;
public TestClass(String testData) {
this.testData = testData;
}
public TestClass() {
this("Test"); //testData defaults to "Test"
}
}
像这样调用:
TestClass testClass1 = new TestClass("Test Data");
TestClass testClass2 = new TestClass();
日期:2020-06-02 22:15:16 来源:oir作者:oir
