我非常了解有关 Java 中构造函数的所有内容,我将其写在下面以确保:
每次创建实例时都初始化类中的所有变量可能很乏味。
在首次创建对象时完成所有设置会更简单。
由于初始化的要求非常普遍,Java 允许对象在创建时自行初始化。
这种自动初始化是通过使用构造函数来执行的。
在创建对象后,在 new 运算符完成之前,构造函数立即自动 c/d。
它们没有返回类型,甚至没有 void。
阅读 Herbert Schildt The Complete Reference,我看到了这一段。
The implicit return type of a class' constructor is the class type itself. It is the constructor's job to initialise the internal state of an object so that the code creating an instance will have a fully initialised, usable object immediately.
我发现自己真的对术语“隐式返回类型”感到困惑,即使很清楚构造函数没有返回类型,甚至没有返回类型。
有人可以吗?
最佳答案
基本上,这只是一段令人困惑的文本。正如您所说,构造函数没有返回类型的概念 - 您可以将它们视为有点像具有相同类型返回类型的方法,但是:
public class Test() {
// This is a spectacularly unhelpful method name.
public Test Test() {
return new Test();
}
}
我会尽量避免将构造函数视为方法——它们的特殊之处太多了。
关于java - Java 中具有隐式返回类型的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25815141/