Constructors in Java

Naveen AnamaneniUpdated · 5 min read

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

Allocate, set defaults, run the constructor, return the reference
Accounts.java▶ Try it
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);
    }
}
Output
Account opened for Navika
Navika: Rs. 5000

How it works

  1. Lines 6 to 13 are a constructor: same name as the class, and no return type, not even void.
  2. Line 17: new BankAccount("Navika", 5000) allocates the object, then runs the constructor with those arguments.
  3. 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.
  4. Lines 10 and 11 copy the parameters into the fields. this.holder means "this object's field holder", 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

KindLooks likeWho writes it
Default constructorBankAccount() {} (invisible)The compiler, only if your class has no constructor at all
No-arg constructorBankAccount() { balance = 0; holder = "Unknown"; }You
Parameterized constructorBankAccount(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:

Compiler output
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 arguments

If you still want new BankAccount(), write a no-arg constructor yourself, often by calling the other one (see "Constructor Overloading and Constructor Chaining").

Defaults.java▶ Try it
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);
    }
}
Output
Unassigned 0
Srihitha 24

Constructor Rules

RuleDetail
NameExactly the class name
Return typeNone; writing void turns it into an ordinary method with the class's name
Called bynew (and other constructors through this(...) or super(...))
Can be overloadedYes, with different parameter lists
Can be privateYes (see "Private Constructors")
Can't bestatic, 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

  1. Easy: Write a Student class with a parameterized constructor for name and roll number, and create two students.
  2. Harder: Make the Student constructor reject an empty name and a roll number below 1, and test it with good and bad values.

Quick check: Constructors

4 questions
1What is the return type of a constructor?
2When does the compiler add a default constructor?
3What do fields hold before the constructor body runs?
4What does holder = holder; inside a constructor with a parameter holder do?

Key Takeaways

Was this tutorial helpful?

Lesson 98 of 482