OBJECT-ORIENTED PROGRAMMING

Java constructors

A constructor is a special class member called automatically when a new object is created. It sets the object's initial attribute values and prepares the object for use.

What is a constructor?

A constructor resembles a method but has two important rules:

  • its name must exactly match the class name;
  • no return type appears before its name, not even void.
public class Knyga {
    String busena;

    Knyga() {
        busena = "Neskaityta";
    }

    public static void main(String[] args) {
        Knyga knyga = new Knyga();
        System.out.println(knyga.busena);
    }
}
Console output

Neskaityta

  1. The constructor name Knyga exactly matches the class name.
  2. There is no voidor other return type before the constructor name.
  3. The expression new Knyga() creates a new object and automatically runs the constructor.
  4. The constructor sets the object's attribute busena to the text Neskaityta.
  5. After the object is created, println() displays the initial state that has already been set.

A constructor with parameters

Parameters let you supply the required initial values when creating an object:

public class Knyga {
    String pavadinimas;
    int puslapiuSkaicius;

    Knyga(String pavadinimas, int puslapiuSkaicius) {
        this.pavadinimas = pavadinimas;
        this.puslapiuSkaicius = puslapiuSkaicius;
    }

    public static void main(String[] args) {
        Knyga knyga = new Knyga("Mažasis princas", 96);

        System.out.println(knyga.pavadinimas);
        System.out.println(knyga.puslapiuSkaicius);
    }
}
Console output

Mažasis princas
96

  1. The constructor expects two pieces of data: the book title and page count.
  2. The arguments passed when creating the object are Mažasis princas and 96.
  3. .pavadinimas means the attribute of the object being created, while the right-hand pavadinimas is the parameter.
  4. Both supplied values are thus stored in the new object.
  5. After the constructor finishes, the prepared object's attributes can be displayed in the console.
this refers to the object being created.

this.pavadinimas is the object's attribute, while the right-hand pavadinimas is the constructor parameter.

Different objects from one constructor

The same constructor can initialize many objects using different arguments:

public class Knyga {
    String pavadinimas;
    int puslapiuSkaicius;

    Knyga(String pavadinimas, int puslapiuSkaicius) {
        this.pavadinimas = pavadinimas;
        this.puslapiuSkaicius = puslapiuSkaicius;
    }

    public static void main(String[] args) {
        Knyga pirma = new Knyga("Mažasis princas", 96);
        Knyga antra = new Knyga("Pepė Ilgakojinė", 160);

        System.out.println(pirma.pavadinimas + ": " + pirma.puslapiuSkaicius);
        System.out.println(antra.pavadinimas + ": " + antra.puslapiuSkaicius);
    }
}
Console output

Mažasis princas: 96
Pepė Ilgakojinė: 160

  1. The first new Knyga(...) call creates an object with the title Mažasis princas.
  2. The second call creates another object with the title Pepė Ilgakojinė.
  3. Both calls run the same constructor but pass different arguments.
  4. Each object stores its own title and page count.
  5. The console therefore shows two different books.

Multiple constructors in a class

A class can have multiple constructors if their parameter counts or types differ. This is called ( constructor overloading).

public class Knyga {
    String pavadinimas;
    int puslapiuSkaicius;

    Knyga(String pavadinimas) {
        this(pavadinimas, 0);
    }

    Knyga(String pavadinimas, int puslapiuSkaicius) {
        this.pavadinimas = pavadinimas;
        this.puslapiuSkaicius = puslapiuSkaicius;
    }

    public static void main(String[] args) {
        Knyga bePuslapiu = new Knyga("Užrašų knygelė");
        Knyga romanas = new Knyga("Mažasis princas", 96);

        System.out.println(bePuslapiu.pavadinimas + ": " + bePuslapiu.puslapiuSkaicius);
        System.out.println(romanas.pavadinimas + ": " + romanas.puslapiuSkaicius);
    }
}
Console output

Užrašų knygelė: 0
Mažasis princas: 96

  1. The first constructor accepts only the book title.
  2. It uses this(pavadinimas, 0) to call the second constructor in the same class, passing a default page count of 0.
  3. The second constructor accepts both the title and the actual page count.
  4. Java selects a constructor based on the number of arguments passed.
  5. this(...) call must be the first constructor statement.

The default constructor

If a class defines no constructors, the Java compiler supplies a default no-argument constructor:

public class Knyga {
    String pavadinimas;

    public static void main(String[] args) {
        Knyga knyga = new Knyga();
        System.out.println(knyga.pavadinimas);
    }
}
Console output

null

  1. The class Knyga defines no constructors.
  2. The Java compiler automatically supplies an empty no-argument constructor.
  3. This makes the expression new Knyga() valid.
  4. The attribute pavadinimas was not assigned a value explicitly, so it receives the default object reference value, null.
  5. println() displays in the console null.
Defining your own constructor prevents the automatic constructor from being generated.

If you still need to create objects without arguments, declare that constructor yourself.

A constructor and a method

Differences between a Java constructor and a method
PropertyConstructorThe method
NameMatches the classDescribes the action performed
Return typeNot writtenRequired, for example, void or int
InvocationAutomatically with newCalled by name
Main purposeInitialize an objectPerform an object or class action

Guidelines for using constructors

  • After the constructor finishes, the object should be in a valid, consistent state.
  • Pass required data as constructor parameters.
  • Avoid long constructors or ones that perform many external operations.
  • Centralize initialization shared by several constructors using this(...).