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 X1:

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 X2:

class B { int x; void B (int n) { x=n; } }

public class X2 { public static void main(String[] args) { B b = new B(); } }

Version X3:

class B { int x; void B () { x=0; } }

public class X3 { public static void main(String[] args) { B b = new B(); } }

Answer: Version X1 does not compile. The error is:

X1.java:3: error: constructor B in class B cannot be applied to given types;
public class X1 { public static void main(String[] args) { B b = new B(0); } }
                                                                 ^
  required: no arguments
  found: int
  reason: actual and formal argument lists differ in length
1 error

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.

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

blog comments powered by Disqus