Java Constructors

TheNewBoston – Constructors

Constructor methods return object instances.

In other words, constructors instantiate (create) objects in memory.

This example class, Account, has two different constructors:

public class Account {
    String name;
    int balance;

    //No argument constructor
    public Account() {
        //Give new object some default values
        this.name = "Jane Doe";
        this.balance = 0;
    }

    //Constructor with two arguments
    public Account(String name, int balance) {
        //Use arguments to fill in object attributes
        this.name = name;
        this.balance = balance;
    }
}

Here is how these constructors would be used in another class:

public class Banking {
    public static void main(String[] args) {
        //use no argument constructor
        Account acc123 = new Account();
        
        //use two argument constructor
        Account acc999 = new Account("Monty", 42);
    }
}

The “no argument” constructor is useful if you want to create generic objects with default values, i.e. each object starts with the same values.

Updating the parameters of the Account objected named acc123 would require additional lines of code.

A constructor with one or more arguments (inputs) allows you to create objects with attributes already defined in one line of code.