Java Constructor's Return Type

By Xah Lee. Date: . Last updated: .

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.

Java

  1. Install
  2. javac java jar javadoc

Java Basics

  1. Print String
  2. Strings
  3. Power Function
  4. Java Types and Type Conversion
  5. Function
  6. Arrays

Class, Inheritance

  1. extends
  2. Constructor
  3. Constructor Return Type
  4. Extending a Class that has Explicit Constructors
  5. static
  6. this
  7. super
  8. Access Specifiers

Abstract class, Interface

  1. abstract
  2. Interface

Package

  1. Package

Misc

  1. Collection, Map
  2. Read/Write File
  3. Convert File Encoding
  4. Complex Numbers in Java
  5. Unicode
  6. Number Literals