MulaiMulai sekarang secara gratis

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.

Latihan ini adalah bagian dari kursus

Introduction to Object-Oriented Programming in Java

Lihat Kursus

Petunjuk latihan

  • Update the constructor for the Car class to take one more parameter: an int year.
  • Set the year inside the constructor to the matching constructor parameters.
  • Pass the values "blue" as a String, "corolla" as a String, and 2022 as an int, to the Car constructor when creating myCar.

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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);
  }
}
Edit dan Jalankan Kode