简体   繁体   中英

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. 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. You can also overload by changing the parameters of a method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM