Question:
Consider the following class definitions in Java:
public class Vehicle {
private String make;
private String model;
private int year;
// Constructor
public Vehicle(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
// Getter methods
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
}
public class Car extends Vehicle {
private int numberOfDoors;
// Constructor
public Car(String make, String model, int year, int numberOfDoors) {
super(make, model, year);
this.numberOfDoors = numberOfDoors;
}
// Getter method
public int getNumberOfDoors() {
return numberOfDoors;
}
}
Write a code snippet that demonstrates the use of constructors to create objects of the Vehicle
and Car
classes. The code should create a Vehicle
object with make "Toyota", model "Camry", and year 2020. Then, it should create a Car
object with make "Honda", model "Accord", year 2019, and numberOfDoors 4. Finally, it should print out the make, model, year, and numberOfDoors of the car object.
// Create a Vehicle object
Vehicle vehicle = new Vehicle("Toyota", "Camry", 2020);
// Create a Car object
Car car = new Car("Honda", "Accord", 2019, 4);
// Print out the details of the car
System.out.println("Make: " + car.getMake());
System.out.println("Model: " + car.getModel());
System.out.println("Year: " + car.getYear());
System.out.println("Number of Doors: " + car.getNumberOfDoors());
The output of the code snippet will be:
Make: Honda
Model: Accord
Year: 2019
Number of Doors: 4
Explanation:
The code snippet begins by creating a Vehicle
object called vehicle
using the Vehicle
class constructor. The constructor takes three arguments: make "Toyota", model "Camry", and year 2020.
Next, a Car
object called car
is created using the Car
class constructor. The constructor is called with four arguments: make "Honda", model "Accord", year 2019, and numberOfDoors 4. The super()
keyword is used to call the constructor of the superclass (Vehicle
) with the make, model, and year arguments.
Finally, the make
, model
, year
, and numberOfDoors
of the car
object are printed using the getter methods getMake()
, getModel()
, getYear()
, and getNumberOfDoors()
respectively.
The output shows the make, model, year, and numberOfDoors of the car object:
Make: Honda
Model: Accord
Year: 2019
Number of Doors: 4