Constructors in Java: Default, No-Arg, Parameterized, Copy & Constructor Overloading
1. Topic Introduction
Creating an object with uninitialized zero values and then calling setData() separately is error-prone—what if a programmer forgets to call setData()? Java solves this with Constructors: special initialization routines that run automatically the instant an object is born with new.
When you buy a new smartphone, the factory runs an automatic initial setup (constructor) before handing it to you—setting default language or applying the exact color/storage you ordered (parameterized constructor). Constructor Overloading is offering multiple setup packages at checkout: a Basic Setup (new Box()), a Cube Setup (new Box(5)), or a Custom Setup (new Box(10, 20, 30)).
void), runs automatically on new, and can be overloaded by changing parameter count/types/order.3. Essential Exam Definitions
new to initialize a newly created object.javac with an empty body ONLY if you define ZERO constructors. A No-Arg Constructor is explicitly written by the programmer with ClassName() { ... }.4. Detailed Technical Explanation & Syntax
Three Strict Rules of Java Constructors
Keep these three compiler rules clear (favorite KTU 3-mark question!):
- Rule 1: Constructor name MUST exactly match the class name (case-sensitive).
- Rule 2: A constructor MUST have NO explicit return type—NOT even
void! (Writingvoid Box() {}turns it into a normal method, NOT a constructor!). - Rule 3: A constructor CANNOT be declared
abstract,static,final, orsynchronized(though it CAN use access modifierspublic,private,protected, or default).
All 4 Constructor Forms in Practice
1. Compiler Default Constructor: Provided automatically ONLY if the class defines NO constructor at all. Crucial trap: the instant you write ANY parameterized constructor Box(int w), the compiler STOPS generating the zero-arg default constructor (new Box() becomes a compile error unless you write it yourself!).
2. Explicit No-Arg Constructor: Box() { width = 1; height = 1; depth = 1; } initializes fixed sensible defaults.
3. Parameterized Constructor: Box(double w, double h, double d) accepts caller arguments at creation.
4. Copy Constructor: Box(Box other) takes an existing object of the same class and copies its state into the new instance.
5. Working Principle: How Constructor Overloading Resolves new Box(...)
javacinspects the arguments passed insidenew Box(...).- Matches argument count and types against all declared constructors (using automatic widening if no exact match exists).
- Emits bytecode calling that specific
<init>constructor immediately after Heap memory allocation.
7. Complete Java Code Examples & Tracing
Box including a Copy Constructor initializing a clone from an existing Box.| 1 | class Cuboid { |
| 2 | double width, height, depth; |
| 3 | |
| 4 | // 1. Explicit No-Arg Constructor |
| 5 | Cuboid() { |
| 6 | width = 1; |
| 7 | height = 1; |
| 8 | depth = 1; |
| 9 | } |
| 10 | |
| 11 | // 2. Single-Parameter Cube Constructor |
| 12 | Cuboid(double side) { |
| 13 | width = height = depth = side; |
| 14 | } |
| 15 | |
| 16 | // 3. Multi-Parameter Constructor |
| 17 | Cuboid(double w, double h, double d) { |
| 18 | width = w; |
| 19 | height = h; |
| 20 | depth = d; |
| 21 | } |
| 22 | |
| 23 | // 4. Copy Constructor (Object as Parameter) |
| 24 | Cuboid(Cuboid existing) { |
| 25 | width = existing.width; |
| 26 | height = existing.height; |
| 27 | depth = existing.depth; |
| 28 | } |
| 29 | |
| 30 | double volume() { |
| 31 | return width * height * depth; |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | public class ComplexAndBoxDemo { |
| 36 | public static void main(String[] args) { |
| 37 | Cuboid unit = new Cuboid(); |
| 38 | Cuboid cube = new Cuboid(4); |
| 39 | Cuboid custom = new Cuboid(2, 5, 10); |
| 40 | Cuboid copy = new Cuboid(custom); |
| 41 | |
| 42 | System.out.println("Unit volume: " + unit.volume()); |
| 43 | System.out.println("Cube volume: " + cube.volume()); |
| 44 | System.out.println("Custom volume: " + custom.volume()); |
| 45 | System.out.println("Copied volume: " + copy.volume()); |
| 46 | } |
| 47 | } |
Unit volume: 1.0 Cube volume: 64.0 Custom volume: 100.0 Copied volume: 100.0
classnewdoublereturn- Adding
voidbefore the constructor name (void Cuboid()makes it a regular method, NOT a constructor!). - Writing a parameterized constructor
Cuboid(double w, double h, double d)without a no-arg constructor, then callingnew Cuboid()-> COMPILE ERROR! - Marking a constructor
staticorfinal.
Comparison Tables
| Property | Constructor | Method |
|---|---|---|
| Purpose | Initializes new object state | Defines object behavior/operation |
| Name | Must match class name exactly | Any valid camelCase identifier |
| Return Type | NO return type (not even void) | Must specify return type or void |
| Invocation | Called automatically by new | Called explicitly via obj.method() |
| Compiler Default | Provided if zero constructors written | Never auto-generated by compiler |
Real-World Applications
- Immutable data models validate required fields inside constructors so invalid objects can never exist.
- Copy constructors clone configuration objects safely without mutating the original.
Important KTU Exam Points
- Remember: Adding ANY parameterized constructor disables the compiler's automatic default constructor!
- Always differentiate Constructor vs Method in tabular form if asked.
Memory Techniques & Revision
- Constructor Rules — 'S-N-N': Same name as class, No return type (not even void), Not static/final/abstract.
Common Pitfalls to Avoid
- Writing
public void Student()and wondering whynew Student()doesn't run the initialization code.
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
Introduction: Constructor overloading is the technique of defining two or more constructors in the same class with different parameter counts, types, or orders so objects can be initialized flexibly.
- Rules of Constructors: Same name as class, no return type (not even
void), invoked automatically onnew, cannot bestatic,final, orabstract. - Constructor vs Method: Constructors initialize state when created and cannot have a return type; methods perform operations on existing objects, require a return type/
void, and are invoked explicitly. - Compiler Rule: If no constructor is written, Java creates an empty default constructor; once any parameterized constructor is defined, the default constructor is NOT added automatically.
| class Box { |
| double w, h, d; |
| Box() { w = h = d = 1; } |
| Box(double side) { w = h = d = side; } |
| } |
Quick Understanding Check
1. A class defines ONLY public Student(String name) { ... }. What happens when another class calls new Student() with no arguments?
2. Which modifiers are ILLEGAL on a Java constructor?