Adding parameters to car class constructor
To use classes dynamically, the class constructor needs to take parameters. You will update the Car class and make the constructor receive parameters, ensuring each instance you create can have different property values.
Diese Übung ist Teil des Kurses
Introduction to Object-Oriented Programming in Java
Anleitung zur Übung
- Update the constructor for the
Carclass to take one more parameter: anintyear. - Set the
yearinside the constructor to the matching constructor parameters. - Pass the values
"blue"as aString,"corolla"as aString, and2022as anint, to theCarconstructor when creatingmyCar.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
class Main {
static class Car {
String color;
String model;
int year;
// Update constructor parameters
Car(String color, String model, ____ ____){
this.color = color;
this.model = model;
// Set the year property
____.____ = ____;
}
}
public static void main(String[] args) {
// Create object instance with correct parameters
Car myCar = new Car("____", "____", ____);
System.out.println(myCar.year);
}
}