Constructors in Java
When a bank opens an account, it doesn't hand over an empty form and hope you fill it in later. It takes your name and opening deposit at the counter, checks them, and only then gives you a working account. A constructor is that counter for your objects: special code that runs once, when the object is created with new, to put it into a valid starting state.
What new Does
public class Accounts {
static class BankAccount {
String holder;
long balance;
BankAccount(String holder, long balance) {
if (balance < 0) {
throw new IllegalArgumentException("Negative opening balance");
}
this.holder = holder;
this.balance = balance;
System.out.println("Account opened for " + holder);
}
}
public static void main(String[] args) {
BankAccount a = new BankAccount("Navika", 5000);
System.out.println(a.holder + ": Rs. " + a.balance);
}
}Account opened for Navika
Navika: Rs. 5000How it works
- Lines 6 to 13 are a constructor: same name as the class, and no return type, not even
void. - Line 17:
new BankAccount("Navika", 5000)allocates the object, then runs the constructor with those arguments. - Lines 7 to 9 validate the input. A negative opening balance throws an exception (exceptions are covered later in the course), so no invalid account ever exists.
- Lines 10 and 11 copy the parameters into the fields.
this.holdermeans "this object's fieldholder", as opposed to the parameter with the same name (see "Java This Keyword").
Try it yourself: create an account with -100. What happens?
Three Kinds of Constructor
| Kind | Looks like | Who writes it |
|---|---|---|
| Default constructor | BankAccount() {} (invisible) | The compiler, only if your class has no constructor at all |
| No-arg constructor | BankAccount() { balance = 0; holder = "Unknown"; } | You |
| Parameterized constructor | BankAccount(String holder, long balance) { ... } | You |
The Default Constructor Disappears
If you write any constructor, the compiler stops adding the default one. Code that used new BankAccount() then breaks:
NoArg.java:2: error: constructor Account in class Account cannot be applied to given types;
public class NoArg { public static void main(String[] a) { Account x = new Account(); } }
^
required: String
found: no argumentsIf you still want new BankAccount(), write a no-arg constructor yourself, often by calling the other one (see "Constructor Overloading and Constructor Chaining").
public class Defaults {
static class Ticket {
String name;
int berth;
Ticket() {
this("Unassigned", 0);
}
Ticket(String name, int berth) {
this.name = name;
this.berth = berth;
}
}
public static void main(String[] args) {
Ticket blank = new Ticket();
Ticket booked = new Ticket("Srihitha", 24);
System.out.println(blank.name + " " + blank.berth);
System.out.println(booked.name + " " + booked.berth);
}
}Unassigned 0
Srihitha 24Constructor Rules
| Rule | Detail |
|---|---|
| Name | Exactly the class name |
| Return type | None; writing void turns it into an ordinary method with the class's name |
| Called by | new (and other constructors through this(...) or super(...)) |
| Can be overloaded | Yes, with different parameter lists |
Can be private | Yes (see "Private Constructors") |
| Can't be | static, final, abstract, or inherited |
Common Mistakes
Adding void. void BankAccount(...) is a method, not a constructor; new BankAccount("Navika", 5000) then fails.
Forgetting this. when names match. holder = holder; assigns the parameter to itself and leaves the field null.
Expecting the default constructor after writing your own. It's only added when there's no constructor at all.
Interview Corner
What is a constructor, and how is it different from a method?
A constructor is special code that initializes a new object; it has the same name as the class, no return type, and runs once when new creates the object. A method can have any name, has a return type (possibly void), and can be called many times on an existing object.
When does the compiler add a default constructor?
Only when the class declares no constructor at all. It's a no-arg constructor that calls super(). As soon as you declare any constructor, the default one is not added.
Practice
- Easy: Write a
Studentclass with a parameterized constructor for name and roll number, and create two students. - Harder: Make the
Studentconstructor reject an empty name and a roll number below 1, and test it with good and bad values.
Key Takeaways
Was this tutorial helpful?