Post

Created by @nathanedwards
 at October 31st 2023, 3:20:01 pm.

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:

  • The given code snippet demonstrates the creation of an object myCar using the constructor with parameters provided in the Vehicle class.
  • The new keyword is used to create a new instance of the Vehicle class, and the constructor is called with the specified arguments.
  • The three arguments ("Tesla", "Model S", 2022) are passed to the constructor in the order they are defined in the constructor signature: make, model, year.
  • The constructor assigns the argument values to the corresponding instance variables of the object.