Hi @Emilio_Parra !!
// Car class
class Car {
// Private Fields
private String carName;
private String carModel;
private String carCapacity;
// Default Constructor
public Car() {
this.carName = "";
this.carModel = "";
this.carCapacity = "";
}
// Parameterized Constructor 1
public Car(String name, String model) {
this.carName = name;
this.carModel = model;
}
// Parameterized Constructor 2
public Car(String name, String model, String capacity) {
this(name, model); // calling parameterized Constructor
this.carCapacity = capacity; // Assigning capacity
}
// Method to return car details
public String getDetails() {
return this.carName + ", " + this.carModel + ", " + this.carCapacity;
}
}
class Demo {
public static void main(String args[]) {
Car car = new Car("Ferrari", "F8", "100");
System.out.println(car.getDetails());
}
}
In this solution, the Car
class has a default constructor and two parameterized constructors.
The default constructor is used to create an instance of the Car
class with default values for its data members (carName
, carModel
, and carCapacity
).
The parameterized constructors allow you to create a Car
object with specific values passed as arguments. By using the parameterized constructors, you can provide values for the data members during object creation.
In the example, the first parameterized constructor takes two arguments (name
and model
) and sets the carName
and carModel
values accordingly.
The second parameterized constructor takes three arguments (name
, model
, and capacity
). It calls the first parameterized constructor (using this(name, model)
) to set the carName
and carModel
values, and then assigns the value of capacity to the carCapacity
data member.
In the provided main
method, a Car object is created using the second parameterized constructor with the arguments “Ferrari”, “F8”, and “100”. This sets the corresponding values for the carName
, carModel
, and carCapacity
data members.
The getDetails
method is used to retrieve the car details (carName
, carModel
, and carCapacity
) as a formatted string.
When the main
method is executed, it prints the details of the created Car object (“Ferrari, F8, 100”) using the getDetails
method.
I hope it helps. Happy Learning