JAVA BASICS IN DETAIL

Java constructor overloading

Constructor overloading lets a class have several constructors with different parameter lists. You can therefore create an object using only the data available at that moment.

Why have several constructors?

Imagine a parcel registration program. Sometimes we know nothing yet, sometimes only the recipient, and sometimes all the parcel details. Instead of three different classes, we can provide three ways to create the same class.

class Siunta {
    String gavejas;
    double svoris;
    boolean skubi;

    Siunta() {
        gavejas = "Nenurodytas";
        svoris = 0.0;
        skubi = false;
    }

    Siunta(String gavejas) {
        this.gavejas = gavejas;
        svoris = 0.0;
        skubi = false;
    }

    Siunta(String gavejas, double svoris, boolean skubi) {
        this.gavejas = gavejas;
        this.svoris = svoris;
        this.skubi = skubi;
    }

    void rodyti() {
        System.out.println(gavejas + ", " + svoris + " kg, skubi: " + skubi);
    }
}

Siunta neuzpildyta = new Siunta();
Siunta laiskas = new Siunta("Ieva");
Siunta deze = new Siunta("Mantas", 4.5, true);

neuzpildyta.rodyti();
laiskas.rodyti();
deze.rodyti();
Console output

Nenurodytas, 0.0 kg, skubi: false
Ieva, 0.0 kg, skubi: false
Mantas, 4.5 kg, skubi: true

  1. new Siunta() has no arguments, so Java selects the no-argument constructor.
  2. new Siunta("Ieva") has one String argument, so the second constructor is selected.
  3. The third call passes String, double and boolean, which match the third constructor.
  4. Selection happens at compile time based on the number, types and order of arguments.

How must constructors differ?

class Bilietas {
    Bilietas(String renginys) { }
    Bilietas(String renginys, int vieta) { }
    Bilietas(int vieta, String renginys) { }
}
There is no console output.

The code only defines three permitted ways to create Bilietas objects.

A constructor's signature depends on its parameters':

  • number;
  • types;
  • type order.

Parameter names do not change the signature. A constructor also has no return type, so that cannot distinguish constructors either.

Delegate shared work with this(...)

Some initial values repeated in the first example. It is more convenient to have one main constructor and delegate to it from the shorter constructors:

class Puodelis {
    String spalva;
    int talpaMl;

    Puodelis() {
        this("baltas", 300);
    }

    Puodelis(String spalva) {
        this(spalva, 300);
    }

    Puodelis(String spalva, int talpaMl) {
        this.spalva = spalva;
        this.talpaMl = talpaMl;
    }
}

Puodelis pirmas = new Puodelis();
Puodelis antras = new Puodelis("mėlynas");

System.out.println(pirmas.spalva + " " + pirmas.talpaMl);
System.out.println(antras.spalva + " " + antras.talpaMl);
Console output

baltas 300
mėlynas 300

  1. The no-argument constructor selects the default color and capacity.
  2. The color constructor passes it to the main constructor and uses this capacity: 300.
  3. The main two-parameter constructor assigns both attributes in one place.
  4. this(...) must be the very first constructor statement.

Learn more about Java’s this keyword

Defining a constructor removes the automatic no-argument constructor

class Knyga {
    String pavadinimas;

    Knyga(String pavadinimas) {
        this.pavadinimas = pavadinimas;
    }
}

Knyga pirma = new Knyga("Altorių šešėly");
// Knyga antra = new Knyga(); // Compilation error
Result

The first object creation works. Uncommenting the second line prevents compilation because the class has no no-argument constructor.

Java supplies an automatic no-argument constructor only if we have defined no constructors ourselves. To support both no-argument and parameterized forms, we must explicitly write both.

Changing parameter names is not enough

class Saskaita {
    Saskaita(String savininkas, int numeris) { }

    // Error: the constructor signature is the same
    Saskaita(String vardas, int kodas) { }
}
Result

The code does not compile because both constructors have the same signature: Saskaita(String, int).

Java considers parameter types and their order, not the names savininkas, vardas, numeris or kodas.

Avoid ambiguous calls

class Pranesimas {
    Pranesimas(String tekstas) { }
    Pranesimas(StringBuilder tekstas) { }
}

// Error: null matches both constructors
Pranesimas pranesimas = new Pranesimas(null);
Result

The code does not compile: null could match both Stringand StringBuilder, so the compiler cannot choose unambiguously.

Overloads should be convenient for people and unambiguous for the compiler. If calls are easily confused, consider clearly named factory methods or a different class structure.

Constructor and method overloading

Differences between constructor and method overloading
PropertyConstructorsMethods
PurposePrepare a new objectPerform an action
NameAlways matches the class nameCan be any valid method name
Return typeNot writtenRequired, including void
InvocationWhen creating an object with new or through this(...)Writing the method name and arguments
SelectionAt compile time, based on arguments and available signatures

More about Java method overloading

What should you remember?

  • Overloaded constructors provide several ways to create an object of the same class.
  • They must differ in parameter count, types or type order.
  • The compiler selects a constructor based on the supplied arguments.
  • this(...) helps avoid repeated initialization logic.
  • this(...) must be the first constructor statement, and circular constructor calls are not allowed.
  • Once any constructor is defined, Java no longer generates an automatic no-argument constructor.