What is constructor?
A constructor is a special method in Java that is used to initialize objects. It is called automatically when an object is created.
Key Features of Constructors:
Same name as the class
No return type (not even void)
Can be default (no arguments) or parameterized
Used to set initial values for object properties
Why Use Constructors?
To set default values
To create objects in a controlled way
To initialize instance variables while object creation
1.default constructor
public class Car {
Car() { // Constructor
System.out.println("Car object is created");
}
public static void main(String[] args) {
Car myCar = new Car(); // Constructor is called here
}
}
2.Parameterized Constructor
public class Car {
String model;
Car(String carModel) {
model = carModel;
}
public void display() {
System.out.println("Car model: " + model);
}
public static void main(String[] args) {
Car myCar = new Car("Honda City");
myCar.display();
}
}
Top comments (0)