Constructors in Java
Definition
In Java, a constructor is a special method that is automatically called when an object is created. Its
name must be the same as the class name and it does not have a return type. Constructors are
used to initialize objects.
Types of Constructors in Java
Default Constructor
A constructor with no parameters. It initializes objects with default values.
class Car {
Car() { // default constructor
System.out.println("Car object created!");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // default constructor is called
}
}
Parameterized Constructor
A constructor that accepts parameters to initialize an object with specific values.
class Car {
String brand;
int year;
Car(String b, int y) { // parameterized constructor
brand = b;
year = y;
}
void display() {
System.out.println(brand + " - " + year);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", 2023);
myCar.display();
}
}
Copy Constructor
A constructor that creates a copy of another object. Java does not provide it by default, but it can be
implemented manually.
class Car {
String brand;
int year;
Car(String b, int y) { // parameterized constructor
brand = b;
year = y;
}
Car(Car other) { // copy constructor
brand = other.brand;
year = other.year;
}
void display() {
System.out.println(brand + " - " + year);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Honda", 2022);
Car car2 = new Car(car1); // copy constructor
car2.display();
}
}
Summary
- Default Constructor → initializes objects with default values.
- Parameterized Constructor → allows initialization with user-defined values.
- Copy Constructor → creates a copy of another object.