Introduce Java Constructors and give examples
In Java, a constructor is a special method that is called when an object is instantiated. Constructors are used to initialize the object's properties and allocate memory for the object. They have the same name as the class and do not have a return type, not even void
.
Default Constructor: A constructor that does not take any parameters. If no constructor is defined in a class, Java provides a default constructor automatically.
Parameterized Constructor: A constructor that takes parameters to initialize an object with specific values.
Here’s a simple example to illustrate both types of constructors:
class Car {
// Attributes
String model;
String color;
int year;
// Default Constructor
public Car() {
model = "Unknown";
color = "Unknown";
year = 0;
}
// Parameterized Constructor
public Car(String model, String color, int year) {
this.model = model;
this.color = color;
this.year = year;
}
// Method to display car details
public void displayDetails() {
System.out.println("Model: " + model);
System.out.println("Color: " + color);
System.out.println("Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
// Creating an object using the default constructor
Car car1 = new Car();
car1.displayDetails(); // Output: Model: Unknown, Color: Unknown, Year: 0
// Creating an object using the parameterized constructor
Car car2 = new Car("Toyota Camry", "Red", 2021);
car2.displayDetails(); // Output: Model: Toyota Camry, Color: Red, Year: 2021
}
}
Class Definition: The Car
class has three attributes: model
, color
, and year
.
Default Constructor: The default constructor initializes the attributes to default values ("Unknown" for model
and color
, and 0
for year
).
Parameterized Constructor: The parameterized constructor allows the user to set the values of the attributes when creating a new Car
object.
Method: The displayDetails
method prints the details of the car.
Main Class: In the Main
class, two Car
objects are created: one using the default constructor and another using the parameterized constructor. The details of both cars are displayed using the displayDetails
method.