Java Constructor's Return Type

, , …,

One of following 3 codes won't compile. See if you can guess which, and fix it. (answer follows.)

Version A:

class B { int x; void B (int n) {x=n;}}
public class x1 { public static void main(String[] args) {B b = new B(0);}}

Version B:

class B { int x; void B (int n) {x=n;}}
public class x2 { public static void main(String[] args) {B b = new B();}}

Version C:

class B { int x; void B () {x=0;}}
public class x3 { public static void main(String[] args) {B b = new B();}}

Answer: Version A does not compile. The java version used is:

java version "1.5.0_13"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_13-b05-241)
Java HotSpot(TM) Client VM (build 1.5.0_13-121, mixed mode, sharing)

Here's why.

Constructor are distinguished from methods by the absence of the return type declaration, not by the class's name. So, in a code like this:

class B { int x; void B (int n) {x=n;}}
public class x2 { public static void main(String[] args) {B b = new B();}}

Java doesn't see any user defined constructor. The void B (int n) {x=n;} is taken as a method because of the existence of the return type. The code compiles fine. With the call new B(), Java simply calls a default constructor it created internally, which does nothing.

Similarly, in this case:

class B { int x; void B (int n) {x=n;}}
public class x1 { public static void main(String[] args) {B b = new B(0);}}

Java doesn't see any user defined constructor. To the compiler, the B class has a user defined method of the same name. Therefore, Java compiler implicitly defined a default constructor for class B that takes no argument. So, the call new B(0) is a compilation error since there is no constructor that takes a argument.

In summary, remember to not give a return type when defining a constructor.

https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html

Thanks to Russell Miles and others on the Apple's Java forum for help.

blog comments powered by Disqus