Java Constructer's Return Type

Xah Lee, 2005-02, 2007-12

One of following 3 codes won't compile. See if you can guess which, and fix it. (answer lies few pages down below.)


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

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

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

Answer: The x1 does not compile.

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)

Thereason for why java gives a compile error for x1 but not others in the above cases is the following.

Constructer 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 constructer. The “void B ...” 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 constructer 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 constructer. To the compiler, the B class has a user defined method of the same name. Java also defined a default constructer for class B that takes no argument. So, the call “new B(0)” is a compilation error since there is no constructer that takes a argument.

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

Reference: Java Lang Spec: classes↗.

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


See also:


Page created: 2005-02.
© 2005 by Xah Lee.
Xah Signet