[英]declaring a return type on a constructor doesn't cause a compilation error
I was writing code in Java and, absent-minded, i typed at some point public void BaseStation()
as the constructor to a BaseStation
class. 我正在用Java编写代码,并且心不在焉,我在某些时候输入public void BaseStation()
作为BaseStation
类的构造函数。 To my surprise, this did not cause a compile-time error and the program got to run. 令我惊讶的是,这并没有导致编译时错误,程序开始运行。 Why is that? 这是为什么? Is there any reason for someone to have a return type to a constructor? 是否有人有一个返回类型的构造函数?
Specifying a return type makes this a method, rather than a constructor. 指定返回类型使它成为一个方法,而不是构造函数。 You can have a method with the same name as the class (though this conflicts the conventions and is bad for readability) 您可以拥有一个与该类同名的方法(虽然这会违反约定并且对可读性不利)
不,编译器只是认为您编写了一个名为BasedStation
的方法,并没有将其解释为构造函数。
This is a type of overloading in Java. 这是Java中的一种重载。 You can also overload by changing the parameters of a method. 您还可以通过更改方法的参数来重载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.