Skip to main content

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.

L1

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 you new the 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

ConstructorMethod
NameMust match classAny legal identifier
Return typeNoneRequired (void or a type)
Called withnew. on object or class
InheritNot inheritedInherited (if visible)
PurposeInitialize new objectBehavior 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 both this() and super() in the same constructor.
L2

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). A private constructor stops new from outside the class.
  • Records generate a canonical constructor; you can compact-customize it (record Point(int x, int y) { public Point { ... } }).
L3

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.

L4

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);
    }
}
L5

Problem Solving Tricks

  • Use this.field = field to 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.
L6

Practice Programs List

  1. Write Rectangle with no-arg (1×1), one-arg (square), and two-arg constructors.
  2. Add a copy constructor and prove the copy does not share mutable state (add a int[] field).
  3. Accidentally write void Rectangle() and watch new Rectangle() still use the default — then fix it.
  4. Chain three constructors with this(...).
  5. Make the no-arg constructor private and construct only via a static factory of.