Constructors and Overloading
Lesson 12 of 20Give your objects a head start: constructors set fields up, and overloading lets one name wear many signatures.
Born ready
A constructor is the first code an object ever runs. Overloading means several constructors compete for the call — Java picks the one whose parameter list fits.
Constructor = setup
Same name as the class, no return type. It runs exactly once, right after new.
Overloading
Several methods (or constructors) with one name but different parameter lists live side by side.
Java picks by args
new Box() matches the no-arg constructor; new Box(5) matches Box(int). No guessing.
Default fields first
Before any constructor line runs, every field starts at its default: 0, false or null.
The life of an object
Follow one new Box(5) from keyword to living reference.
Two constructors, one choice
Watch Java resolve the overload: the int argument in new Box(5) selects Box(int), not Box().
1public class BoxDemo {2public static void main(String[] args) {3Box a = new Box(5);4System.out.println("a = " + a.size);5}6}78class Box {9int size;1011Box() {12size = 1;13}1415Box(int s) {16size = s;17}18}
The JVM loads BoxDemo plus the Box blueprint — which carries TWO constructors with the same name but different parameter lists.
Match the call to the constructor
Which overload answers each call?
Two greeters, two constructors
Which overload runs for each creation?
1public class GreetDemo {2public static void main(String[] args) {3Greeter g1 = new Greeter();4Greeter g2 = new Greeter("Bo");5System.out.println(g1.name + " " + g2.name);6}7}89class Greeter {10String name;1112Greeter() {13name = "Anon";14}1516Greeter(String n) {17name = n;18}19}
Hint: No arguments pick the no-arg constructor; a String argument picks Greeter(String).
Key takeaways
A constructor runs once, immediately after new, to set the object up.
Overloading = one name, several parameter lists; Java picks the best match.
Fields hold default values (0, false, null) until the constructor assigns them.
If you write no constructor at all, Java silently provides an empty no-arg one.
The argument list — not the name, not the return type — decides which overload runs.