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
| Type | Purpose | Example | Note |
|---|---|---|---|
| Default | No-arg init | Box() {} | Auto-provided if none defined |
| Parameterized | Custom init | Box(int s) {} | |
| Copy | Clone object | Box(Box b) {} | Manual; no built-in |
| Chained | Reuse logic | this(...) | 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.
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());
}
}
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.
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();
}
}
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();
}
}
Aman 18
Riya 25
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();
}
}
Dog created
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());
}
}
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.
No — constructors cannot have a return type.
A constructor initializes an object and has the class name; a method describes behavior and can return a value.
No — but they can be invoked from a subclass via
super().
Yes — used in singleton and factory patterns.
Calling one constructor from another using
this() (same class) or super() (parent class).
FAQ
Only when no constructor is explicitly defined. Otherwise, Java does not auto-generate one.
Yes — they follow the same rules as method overloading.
No — final is meaningless for constructors as they aren't inherited.
Yes — using
this(args) at the first line.
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
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
Quick Reference
| Keyword / Concept | Meaning | Used For | Java Since |
|---|---|---|---|
| Constructor | Constructor concept | Core Java | 1.0 |
| class | Blueprint of objects | OOP | 1.0 |
| static | Class-level member | Utilities | 1.0 |
| final | Constant / no override | Immutability | 1.0 |
| public | Accessible everywhere | API exposure | 1.0 |
| private | Class-only access | Encapsulation | 1.0 |
Related Topics
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.