Constructors in Java
In Java, constructors are special methods used to initialize objects of a class. They are called automatically when an object is created and help set the initial state of the object.
What is a Constructor?
- A constructor has the same name as the class.
- It does not have a return type, not even
void. - Used to initialize object attributes when an object is created.
Syntax:
class ClassName {
// Constructor
ClassName() {
// Initialization code
}
}
Note: If you don’t define a constructor, Java provides a default constructor automatically.
Types of Constructors

A. Default Constructor
- Provided by Java if no constructor is explicitly defined.
- No parameters.
- Initializes objects with default values.
Example – Default Constructor Provided by Java:
class Car {
String color;
int speed;
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Default constructor
System.out.println("Color: " + myCar.color); // null
System.out.println("Speed: " + myCar.speed); // 0
}
}
Note: Default values: null for objects, 0 for numeric types, false for boolean.
B. Parameterized Constructor
- Takes parameters to initialize object attributes.
- Allows you to create objects with custom values.
Example – Parameterized Constructor:
class Car {
String color;
int speed;
// Parameterized Constructor
Car(String c, int s) {
color = c;
speed = s;
}
void display() {
System.out.println(color + " car is driving at " + speed + " km/h");
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Red", 80);
Car car2 = new Car("Blue", 120);
car1.display();
car2.display();
}
}
Output:
Red car is driving at 80 km/h
Blue car is driving at 120 km/h
Note: Parameterized constructors make object creation more flexible and readable.
Constructor Overloading
Java allows multiple constructors in the same class with different parameter lists. This is called constructor overloading.
Example:
class Car {
String color;
int speed;
Car() { // Default
color = "White";
speed = 0;
}
Car(String c) { // Single parameter
color = c;
speed = 50;
}
Car(String c, int s) { // Two parameters
color = c;
speed = s;
}
void display() {
System.out.println(color + " car at " + speed + " km/h");
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
Car car2 = new Car("Red");
Car car3 = new Car("Blue", 100);
car1.display();
car2.display();
car3.display();
}
}
Output:
White car at 0 km/h
Red car at 50 km/h
Blue car at 100 km/h
Points to Remember
- Constructor name = class name, no return type.
- Default constructor is provided automatically if no constructor is defined.
- Parameterized constructors allow custom initialization.
- Constructor overloading helps initialize objects in different ways.
- Called automatically when an object is created.
