Constructor vs Method

Naveen AnamaneniUpdated · 4 min read

A constructor looks a lot like a method: a name, parentheses with parameters, and a body in braces. But they do different jobs. A constructor builds an object once; a method does something with an object that already exists, as many times as you like. Mixing them up leads to a classic bug where a "constructor" silently becomes a method.

Point by Point

ConstructorMethod
PurposeInitialize a new objectPerform an action on an object (or the class)
NameMust be the class nameAny valid name, usually a verb
Return typeNone, not even voidRequired (void if nothing is returned)
When it runsOnce, when new creates the objectEvery time it's called
How it's callednew Ticket(...), or this(...) / super(...) from another constructorticket.print() or Ticket.fareFor(300)
Added by the compilerA default one, if you write noneNever
Inherited by subclassesNoYes (unless private)
Can be overriddenNoYes (unless final, static or private)
Can be static, final, abstractNoYes
Can be overloadedYesYes

Both in One Class

TicketDemo.java▶ Try it
public class TicketDemo {
    static class Ticket {
        String name;
        int berth;
        int changes;
 
        Ticket(String name, int berth) {
            this.name = name;
            this.berth = berth;
        }
 
        void moveTo(int newBerth) {
            berth = newBerth;
            changes++;
        }
    }
 
    public static void main(String[] args) {
        Ticket t = new Ticket("Navika", 23);
        t.moveTo(31);
        t.moveTo(32);
        System.out.println(t.name + " in berth " + t.berth
                + " after " + t.changes + " changes");
    }
}
Output
Navika in berth 32 after 2 changes

The constructor ran once, at new. The method moveTo ran twice on the same object.

The void Trap

Adding void to a "constructor" turns it into an ordinary method that happens to share the class's name. The compiler then adds the default constructor, and your setup code never runs:

VoidTrap.java▶ Try it
public class VoidTrap {
    static class Coach {
        int seats;
 
        void Coach() {
            seats = 72;
        }
    }
 
    public static void main(String[] args) {
        Coach c = new Coach();
        System.out.println("Seats: " + c.seats);
    }
}
Output
Seats: 0

How it works

  1. Line 5 has a return type, void, so it's a method named Coach, not a constructor.
  2. The class now has no constructor, so the compiler adds an empty default one.
  3. new Coach() runs that empty constructor; seats keeps its default, 0.

Try it yourself: remove void from line 5 and run it again.

Common Mistakes

Calling a constructor like a method. t.Ticket("Navika", 23) doesn't compile; constructors run only through new, this(...) or super(...).

Expecting constructors to be inherited. A subclass must declare its own constructors (see "Constructor Calls in Inheritance").

Putting long-running work in a constructor. Keep constructors to setup and validation; heavy work belongs in methods.

Interview Corner

What are the differences between a constructor and a method?

A constructor has the same name as the class, no return type, runs once when new creates an object, and isn't inherited or overridden. A method can have any name, must declare a return type (or void), can be called any number of times, and can be inherited, overridden, static, final or abstract.

Can a constructor return a value?

No. It has no return type. It may use a bare return; to finish early, but the result of new is always the reference to the new object.

Practice

  1. Easy: For a Movie class, decide which of these should be the constructor and which should be methods: setting the title, adding a rating, printing details.
  2. Harder: Write a Counter class whose constructor sets a starting value and whose method next() returns the next value each time. Call next() three times.

Quick check: Constructor vs method

4 questions
1Which has no return type at all?
2How many times does a constructor run for one object?
3What is void Coach() { ... } inside class Coach?
4Are constructors inherited by subclasses?

Key Takeaways

Was this tutorial helpful?

Lesson 99 of 482