Java Learning: Default Constructor

Spread the love

The objective of a constructor is to create an object from a class blueprint.
Since the main idea of this action is to create and initialize an object, it makes sense to use the class’s name as the method’s name.
This is a special method since it has no explicit return type. I say explicit because it returns a reference to the object created and allocated in the heap. We could say it returns this, the reserved word that can be used inside the class to reference the current object. Some languages call it self, which seems very appropriate.
Another distinction from other method calls is the word new; this is how the compiler knows we are targeting a constructor method and not a local method.

BankAccount ba = new BankAccount(); // OK: the word new signals to choose a constructor method

BankAccount ba = BankAccount(); // ERROR: Will try to call a local method

All classes should have at least one constructor, meaning you should have a method with no return type and with the same class’s name.
Most of the classes don’t need, at the start, specific logic or values to be initialized when the object is created. To avoid always writing an empty constructor, if none is provided, the Java compiler assumes a default constructor exists.

class BankAccount {
	private String customerId;
	private String customerName;

	// optional
	public BankAccount() {}
}

class SavingsAccount {
	// There is an empty constructor here!
}


public class Finances {
	public static void main(String... args) {
		BankAccount ba = new BankAccount();
		SavingsAccount sa = new SavingsAccount();
	}
}

Leave a Reply

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