Java OOP
Constructors
Complete lesson for Constructors using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Constructors
Section: Java OOP. Default, no-arg, and parameterized constructors, overloading, and this() chaining.
What a constructor is
- A constructor has the **same name as the class**, no return type (not even
void), and runs when younewthe object. - If you write no constructor, the compiler supplies a **default** public no-arg constructor that calls
super(). - If you write *any* constructor, the default disappears. Then
new Foo()fails unless you also write a no-arg constructor.
public class User {
String name;
int age;
User() {
this("guest", 0); // must be first statement
}
User(String name, int age) {
this.name = name;
this.age = age;
}
public static void main(String[] args) {
User a = new User();
User b = new User("Isha", 20);
System.out.println(a.name + " / " + b.name);
}
} Constructor vs method
| Constructor | Method | |
|---|---|---|
| Name | Must match class | Any legal identifier |
| Return type | None | Required (void or a type) |
| Called with | new | . on object or class |
| Inherit | Not inherited | Inherited (if visible) |
| Purpose | Initialize new object | Behavior after creation |
Overloading and this()
- You can overload constructors by parameter list.
this(args)calls another constructor of the **same** class and must be the first statement. super(args)calls the parent constructor and is also first-statement only. You cannot use boththis()andsuper()in the same constructor.
Advanced — Constructors
Initialization order and copies
- Order: superclass constructors → instance field initializers / instance blocks (in source order) → constructor body.
- Java has no C++ copy constructor. Write a copy constructor yourself (
User(User other)) or a copy factory.clone()is outdated and error-prone. - Constructors can be
private(singletons, factories, enums). Aprivateconstructor stopsnewfrom outside the class. - Records generate a canonical constructor; you can compact-customize it (
record Point(int x, int y) { public Point { ... } }).
Tricky Interview Points
Q1) What is a default constructor?
Answer The no-arg constructor the compiler adds only when you declare none. It invokes super() and leaves fields at defaults.
Q2) Can a constructor return a value?
Answer No return type. You do not write return obj;. new already yields the reference.
Q3) Why does new Student() fail after I added Student(String)?
Answer Declaring any constructor suppresses the default. Add Student() if you still need no-arg construction.
Q4) What must be first in a constructor body?
Answer Optional this(...) or super(...). After that, normal statements. Field initializers run before the rest of the body (after super).
Q5) Are constructors inherited?
Answer No. A subclass must call some super constructor (implicit super() or explicit super(args)).
Q6) Constructor vs method with the same name as the class?
Answer If you add a return type it becomes a method, not a constructor — a nasty bug: public void User() { } is a method.
Simple Programs
Overloaded constructors and a copy constructor
public class Box {
final int w, h;
Box(int side) {
this(side, side);
}
Box(int w, int h) {
this.w = w;
this.h = h;
}
Box(Box other) {
this(other.w, other.h);
}
public static void main(String[] args) {
Box a = new Box(4);
Box b = new Box(a);
System.out.println(a.w + "x" + a.h);
System.out.println(b.w + "x" + b.h);
}
} Problem Solving Tricks
- Use
this.field = fieldto disambiguate parameters. Or pick different parameter names. - Keep constructors cheap; do I/O in factories if you need to throw checked exceptions cleanly.
- Validate arguments early (
if (age < 0) throw ...). - Prefer constructor chaining over duplicated assignment lists.
Practice Programs List
- Write
Rectanglewith no-arg (1×1), one-arg (square), and two-arg constructors. - Add a copy constructor and prove the copy does not share mutable state (add a
int[]field). - Accidentally write
void Rectangle()and watchnew Rectangle()still use the default — then fix it. - Chain three constructors with
this(...). - Make the no-arg constructor
privateand construct only via a static factoryof.