Declaring return type in constructor does not cause compilation error

I wrote Java code and, absent-mindedly, typed at some point public void BaseStation() as a constructor for the BaseStation class. To my surprise, this did not cause an error during compilation, and the program was launched. Why is this? Is there a reason someone has a return type for the constructor?

+4
source share
3 answers

Setting the return type makes this method, not a constructor. You may have a method with the same name as the class (although this is against the conventions and is poorly read)

+7
source

No, the compiler just thinks that you wrote a method called BasedStation and do not interpret it as a constructor.

+2
source

This is a type of overload in Java. You can also overload by changing the method parameters.

-1
source

Source: https://habr.com/ru/post/1402028/


All Articles