Java: Constructor

By Xah Lee. Date: . Last updated: .

In Java, if you want a piece of code to run automatically when your class is called for the first time (i.e. when it is instantiated), you need to do 2 things:

Such a method is called a constructor.

The purpose of constructor is basically to set some variables when the object is created for the first time. This practice is called intialization.

// Example of defining a constructor and using it to create a object
class C2 {
    C2 (int n) { System.out.println("i'll do this and that!");}
}

class C1 {
    public static void main(String[] arg) {
        C2 x = new C2(3);
    }
}

More Than One Constructor

There can be more than one constructors in a class.

When you have more than one constructors, the constructors are different from each other by their parameters declaration. When the class is initialized, Java will call the right constructor that matches the given arguments and type. We say that Java's constructor is polymorphic.

Example:

// a class with 3 constructors, differ by their parameters
class T2 {
    T2 () { System.out.println("empty arg called!");}
    T2 (int n) { System.out.println("int one called!");}
    T2 (double n) { System.out.println("double one called!");}
}

class T1 {
    public static void main(String[] arg) {
// creating 3 objects of T2.
// when each object are created, Java automatically calls the right constructor by matching the arguments and type.
        T2 x1 = new T2();
        T2 x2 = new T2(3);
        T2 x3 = new T2(3.0);
    }
}

The above is a simple example. In general, your constructors's parameters may be other objects.

WARNING: remember, a constructor must have:

  1. The same name as the class.
  2. No return type declaration.

No Constructor Means Default Constructor

Every class has a constructor even though none are defined. When a class does not define any constructor, the Java compiler actually automatically creates a do-nothing constructor with no parameter. So, if a class B does not define any constructor and when a object of B is created B b = new B(), internally Java calls the default constructor B(), which does nothing.

This internal stuff is important to know. Because for example, once a constructor is defined by the programer, Java no longer internally creates this default no-argument constructor.

So, for example, if you have a class B that has a constructor B (int n), you cannot create a object of B by new B() because you didn't define it and Java didn't create it automatically. It is a compilation error.

/*
This example shows a class B with a user defined constructor.
However, the when a obj B is created by 「new B()」, it creates a
compiler error because the Java compiler saw the existence of a user
defined constructor so it did not automatically create the
no-parameter and do-nothing constructor.

remove the user defined constructor, and the code compiles.
 */
class B68 {
    int x;
    B68 (int n) {
        x=n;
        System.out.println("constructor 'B68 (int n)' called!");
    }
}

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

Here's the error:

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

Note that constructor does not have a return type declaration. If you define a method that has the same name as the class, but also has a return type declaration, then Java will NOT consider that as a constructor. See: constructor and void .

Also, constructors are not inherited. See: inheritance with constructors .