NBKRIST JavaHub

Constructors & Constructor Overloading (Java)

A constructor is the very first block of code that executes when an object is created. It sets the initial state of the object and ensures the object enters the program in a valid, predictable condition.

1. What is a Constructor?

A constructor is a special method that has the same name as the class and no return type. It runs automatically when we create an object using new. Its job is simple but powerful — initialize the object.

class Car { Car() { System.out.println("Car object created"); } } public class Test { public static void main(String[] args) { Car c = new Car(); } }
Output: Car object created

2. Default Constructor

If you do not define any constructor, Java automatically provides a default constructor. It assigns default values based on data types (0, null, false).

class Student { String name; // null int age; // 0 } public class Demo { public static void main(String[] args) { Student s = new Student(); System.out.println(s.name); System.out.println(s.age); } }
Output: null 0

3. Parameterized Constructor

Parameterized constructors allow passing values to an object at the time of creation, making object initialization meaningful and dynamic.

class Employee { String name; int id; Employee(String n, int i) { name = n; id = i; } } public class Demo { public static void main(String[] args) { Employee e = new Employee("Hari", 101); System.out.println(e.name + " " + e.id); } }
Output: Hari 101

4. Constructor Overloading

Constructor overloading means creating multiple constructors within the same class with different parameter lists. It provides flexibility in object creation.

class Box { int length, width, height; Box() { length = width = height = 1; } Box(int side) { length = width = height = side; } Box(int l, int w, int h) { length = l; width = w; height = h; } } public class Test { public static void main(String[] args) { Box b1 = new Box(); Box b2 = new Box(5); Box b3 = new Box(2,3,4); System.out.println(b1.length+","+b2.length+","+b3.length); } }
Output: 1,5,2

Practice Questions – Click to Reveal Answers

1️⃣ What is a constructor?
A constructor initializes objects and has the same name as the class.
2️⃣ Define default constructor.
A constructor automatically provided by Java when no constructor is written.
3️⃣ What is constructor overloading?
Multiple constructors with different parameter lists in the same class.
4️⃣ Why are parameterized constructors used?
To initialize objects with user-defined values.

Quick Summary