Java Learning – Multiple Constructors

Spread the love

A Java class can have multiple constructors. A default no-parameter constructor, as described in a previous post, and overloading constructors, as many as necessary.

When a class doesn’t have any constructors, Java simply provides a default constructor, but as soon as another constructor is written, the default constructor is not available anymore, unless it is explicitly written.

Check below the differences between the BankAccount and SavingsAccount constructors.

class BankAccount {
	private String customerId;
	private String customerName;

	// The default constructor
	public BankAccount() {}

	// An explicit constructor
	public BankAccount(String customerId, String customerName) {
		this.customerId = customerId;
		this.customerName = customerName;
	}
}

class SavingsAccount {
	
	// ATTENTION: When a constructor with parameters exists, the default constructor is not available anymore.
	// The public SavingsAccount() {} is not available 
	public SavingsAccount(double initialBalance) {
		// some business stuff here
	}
}


public class Finances {
	public static void main(String... args) {
		BankAccount ba = new BankAccount();
		SavingsAccount sa = new SavingsAccount(); // ERROR! Do you know why?
	}
}

The BankAccount has a default constructor explicitly defined in the class. Adding another constructor doesn’t have any side effects on the existing code. It is just overloading constructors, similar to overloading methods.

The SavingsAccount doesn’t have a default constructor explicitly defined, but it exists implicitly until another constructor is added. When this happens, Java doesn’t provide the default constructor.

The main purpose of a constructor is to make sure the required information is provided to successfully initialize an object. For instance, for a Point to exist, the coordinates (x,y) must be provided; it doesn’t make sense to create a point without at least the x and the y.
If the default constructor was always in the class, even when the user didn’t write it, it would be possible to create a Point without values for the coordinates.

A good tip to understand these kinds of questions is to always keep an eye on business cases or semantic inconsistencies.

Leave a Reply

Your email address will not be published. Required fields are marked *