Constructor in Java Tutorial
Chapter 18 · Java Programming Series
PBA Institute 11 min read Beginner to Intermediate 2024

Constructor in Java

A constructor is a special method that initializes a newly created object. It has the same name as the class and no return type. Constructors set up an object's initial state and can be overloaded to support multiple ways of creating an instance.

Key Features

🆕

Auto-Invoked

Runs immediately when new is used.

📛

Same as Class Name

Identifies the constructor.

🚫

No Return Type

Not even void.

🧩

Overloadable

Multiple constructors with different parameter lists.

🔁

Chaining

Use this() to call another constructor in the same class.

👨‍👩‍👦

super()

Call the parent constructor in a subclass.

Syntax

  • Default: ClassName() { … }
  • Parameterized: ClassName(int x, String y) { … }
  • Copy: ClassName(ClassName other) { … }
  • Chain: this(args); or super(args); at the first line.

Constructor Types

TypePurposeExampleNote
DefaultNo-arg initBox() {}Auto-provided if none defined
ParameterizedCustom initBox(int s) {}
CopyClone objectBox(Box b) {}Manual; no built-in
ChainedReuse logicthis(...)First line

Detailed Explanation & First Example

Let's start with a hands-on example. The program below shows the core idea behind Constructor in just a few lines of Java. Read it line by line and observe how Java executes each statement in order.

Default and Parameterized Constructor
class Box
{
    int side;

    Box()          { side = 10; }
    Box(int s)     { side = s;  }

    int volume() { return side * side * side; }
}

class Main
{
    public static void main(String args[])
    {
        Box a = new Box();
        Box b = new Box(5);

        System.out.println(a.volume());
        System.out.println(b.volume());
    }
}
Output 1000
125

Examples — Beginner to Advanced

The following examples progress from simple to more practical patterns. Try each in your IDE, change the inputs and observe the output. This is the fastest way to internalize the concept.

Copy Constructor
class Point
{
    int x, y;

    Point(int x, int y) { this.x = x; this.y = y; }
    Point(Point p)      { this.x = p.x; this.y = p.y; }

    void show() { System.out.println(x + "," + y); }
}

class Main
{
    public static void main(String args[])
    {
        Point p1 = new Point(3, 4);
        Point p2 = new Point(p1);

        p2.show();
    }
}
Output 3,4
Constructor Chaining with this()
class Person
{
    String name;
    int    age;

    Person()                       { this("Unknown", 0); }
    Person(String n)               { this(n, 18); }
    Person(String n, int a)        { name = n; age = a; }

    void show() { System.out.println(name + " " + age); }
}

class Main
{
    public static void main(String args[])
    {
        new Person().show();
        new Person("Aman").show();
        new Person("Riya", 25).show();
    }
}
Output Unknown 0
Aman 18
Riya 25
super() to Parent Constructor
class Animal
{
    Animal() { System.out.println("Animal created"); }
}

class Dog extends Animal
{
    Dog() { super(); System.out.println("Dog created"); }
}

class Main
{
    public static void main(String args[])
    {
        new Dog();
    }
}
Output Animal created
Dog created
Constructor Overloading
class Rect
{
    int w, h;

    Rect()              { w = h = 1; }
    Rect(int s)         { w = h = s; }
    Rect(int w, int h)  { this.w = w; this.h = h; }

    int area() { return w * h; }
}

class Main
{
    public static void main(String args[])
    {
        System.out.println(new Rect().area());
        System.out.println(new Rect(5).area());
        System.out.println(new Rect(3, 4).area());
    }
}
Output 1
25
12

Notes & Tips

  • If no constructor is defined, Java provides a default no-arg constructor.
  • Constructors do not have a return type — not even void.
  • this(...) and super(...) must be the first statement in a constructor.
  • Use private constructors to enforce singletons or factory patterns.
  • Constructors are not inherited, but they are called from subclasses via super().

Real-World Use Cases

Object Initialization

Set up required fields before use.

Multiple Init Modes

Overload to support different ways to create the object.

Immutable Objects

Set all final fields once in the constructor.

Object Cloning

Copy constructor to create a duplicate.

Practice Questions

Reading is not enough — practice solidifies knowledge. Try every question below in your own editor before peeking at any solution.

  • Q1. Build a Student class with three constructors (default, name only, full).
  • Q2. Demonstrate constructor chaining using this().
  • Q3. Create a copy constructor for a Book class.
  • Q4. Show why a default constructor is auto-provided.
  • Q5. Use super() to initialize parent fields from a subclass constructor.

Interview Questions

These are the most common questions asked in Java interviews on this topic. Memorize the concept, not just the answer — interviewers often follow up with edge cases.

Q1 Can a constructor return a value?
No — constructors cannot have a return type.
Q2 What is the difference between a method and a constructor?
A constructor initializes an object and has the class name; a method describes behavior and can return a value.
Q3 Can constructors be inherited?
No — but they can be invoked from a subclass via super().
Q4 Can a constructor be private?
Yes — used in singleton and factory patterns.
Q5 What is constructor chaining?
Calling one constructor from another using this() (same class) or super() (parent class).

FAQ

FAQ 1 Is the default constructor always present?
Only when no constructor is explicitly defined. Otherwise, Java does not auto-generate one.
FAQ 2 Can constructors be overloaded?
Yes — they follow the same rules as method overloading.
FAQ 3 Can a constructor be final?
No — final is meaningless for constructors as they aren't inherited.
FAQ 4 Can a constructor call another constructor?
Yes — using this(args) at the first line.
FAQ 5 Are constructors thread-safe?
Object construction is safe per object; visibility issues can arise with shared references published unsafely.

Common Mistakes to Avoid

Even experienced developers slip on the same pitfalls. Watch out for these classic mistakes while working with Constructor in Java:

  • Forgetting the semicolon ; at the end of statements while using Constructor.
  • Mixing up similar method names — read Java docs before using new APIs related to Constructor.
  • Ignoring compiler warnings — they often hint at bugs that will appear later in production.
  • Hard-coding values that should come from configuration files or environment variables.
  • Not handling edge cases: empty inputs, very large inputs, negative numbers and null references.
  • Skipping unit tests — small tests prevent big regressions, especially around control flow.

At-a-Glance

Advantages
Readable Reusable Testable Standardized
Watch Out
Edge Cases Null Safety Performance Memory
Java Version
JDK 8+ JDK 11 JDK 17 LTS JDK 21 LTS
Pair With
Class and Object Inheritance OOP Best Practices

Best Practices

📐

Follow Conventions

Use camelCase for variables, PascalCase for classes, UPPER_SNAKE for constants.

🧪

Write Tests

Cover happy path and edge cases with JUnit before shipping changes to production.

🧹

Keep Methods Short

A method should do one thing and fit on a single screen. Refactor when it grows.

🔍

Validate Inputs

Never trust user input. Validate at the boundary, fail fast and log meaningfully.

📝

Comment the Why

Comments should explain why a decision was made — not what the code does line by line.

♻️

Refactor Often

Small frequent refactors are cheap and safe; big rewrites are risky and expensive.

Pro Tips

TIP 01 Use clear, descriptive identifiers when writing code involving Constructor — your future self will thank you.
TIP 02 Run small experiments in jshell (Java's REPL) to test ideas before committing them to a project.
TIP 03 Read the official java.lang and java.util documentation. The standard library is huge and surprisingly powerful.
TIP 04 Combine this topic with unit testing (JUnit 5) — it forces you to think about edge cases.
TIP 05 Practice with online judges (HackerRank, LeetCode) to internalise the patterns used in real interviews.

Quick Reference

Keyword / ConceptMeaningUsed ForJava Since
ConstructorConstructor conceptCore Java1.0
classBlueprint of objectsOOP1.0
staticClass-level memberUtilities1.0
finalConstant / no overrideImmutability1.0
publicAccessible everywhereAPI exposure1.0
privateClass-only accessEncapsulation1.0

Related Topics

PREV Class and Object — strengthens your understanding of the previous building block.
NEXT Inheritance — the natural progression after mastering Constructor.
OOP Object Oriented Programming — Class, Object, Inheritance, Polymorphism, Encapsulation, Abstraction.
DSA Data Structures & Algorithms — apply this topic in real coding-interview challenges.
STD LIB Java Standard Library — explore java.util, java.lang and java.io.

Summary

Constructors initialize newly created objects. They share the class name, have no return type, and may be overloaded. Use this() for chaining within a class and super() to call the parent constructor. Constructors give you fine-grained control over how objects come to life.

Continue Learning