开始使用免费开始使用

为 Car 类创建构造方法

能够为类的属性设置取值非常重要,只有这样才能有效使用这些属性。请为 Car 类创建一个构造方法,并确保它的属性被赋予合理的初始值。

请记住当我们创建实例时,类的构造方法总会被调用。

本练习是课程的一部分

Java 面向对象编程入门

查看课程

练习说明

  • Car 类创建一个不带参数的构造方法。
  • 在构造方法中,将 color 属性设置为字符串 "red"
  • 在构造方法中,将 year 属性设置为整数 2019
  • 打印 myCar 对象实例的 color 属性。

交互式实操练习

通过完成这段示例代码来试试这个练习。

class Main {  

  static class Car {
      String color;
      String model;
      int year;
      
      // Create constructor method	
      ____() {        
          this.model = "camry";
          // Assign the values for the color and year properties
          ____.____ = "____";
          ____.____ = ____;
      }

  }
  
  public static void main(String[] args) {
    Car myCar = new Car();
    // Print the "color" property
    System.out.println(____.____);
  }
}
编辑并运行代码