Question:
Consider the following class definition:
public class Vehicle {
private String make;
private String model;
private int year;
// Constructor with parameters
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;
}
// Setter methods
public void setMake(String make) {
this.make = make;
}
public void setModel(String model) {
this.model = model;
}
public void setYear(int year) {
this.year = year;
}
}
Write a Java code snippet to create an object of the Vehicle
class, using the constructor with parameters. The object should represent a vehicle with the following details:
Make: "Tesla" Model: "Model S" Year: 2022
Assign this object to a variable named myCar
.
Answer:
// Code snippet to create an object of Vehicle class with constructor
Vehicle myCar = new Vehicle("Tesla", "Model S", 2022);
Explanation:
myCar
using the constructor with parameters provided in the Vehicle
class.new
keyword is used to create a new instance of the Vehicle
class, and the constructor is called with the specified arguments.make
, model
, year
.