Clean β’ Professional
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.
void.Syntax:
class ClassName {
// Constructor
ClassName() {
// Initialization code
}
}
Note: If you donβt define a constructor, Java provides a default constructor automatically.

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.
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.
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