Constructor vs Method
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
| Constructor | Method | |
|---|---|---|
| Purpose | Initialize a new object | Perform an action on an object (or the class) |
| Name | Must be the class name | Any valid name, usually a verb |
| Return type | None, not even void | Required (void if nothing is returned) |
| When it runs | Once, when new creates the object | Every time it's called |
| How it's called | new Ticket(...), or this(...) / super(...) from another constructor | ticket.print() or Ticket.fareFor(300) |
| Added by the compiler | A default one, if you write none | Never |
| Inherited by subclasses | No | Yes (unless private) |
| Can be overridden | No | Yes (unless final, static or private) |
Can be static, final, abstract | No | Yes |
| Can be overloaded | Yes | Yes |
Both in One Class
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");
}
}Navika in berth 32 after 2 changesThe 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:
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);
}
}Seats: 0How it works
- Line 5 has a return type,
void, so it's a method namedCoach, not a constructor. - The class now has no constructor, so the compiler adds an empty default one.
new Coach()runs that empty constructor;seatskeeps 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
- Easy: For a
Movieclass, decide which of these should be the constructor and which should be methods: setting the title, adding a rating, printing details. - Harder: Write a
Counterclass whose constructor sets a starting value and whose methodnext()returns the next value each time. Callnext()three times.
Key Takeaways
Was this tutorial helpful?