class Dog {
public Dog() { // constructor for the class Dog
}
public void Dog() { // method with the name Dog
}
public void method() { // method with the name method
}
// invalid code
// causes an error because the return type for the method is missing
// and isn't a constructor because it hasn't the same name as the class.
public method() {
}
}
# 1 楼答案
Java有严格的语法,也适用于Method Declarations和Constructor Declarations
方法的语法总是需要返回类型或void。 构造函数只有在与类同名时才有效
以你为例:
# 2 楼答案
构造函数的存在是为了构建对象,而不是方法
方法需要返回类型,因为它们从现有对象返回某些内容(即使返回类型为void),但构造函数用于构建对象,因此它不需要任何返回类型,因为调用对象时对象不存在