【问题标题】:Creating classes in Java在 Java 中创建类
【发布时间】:2018-11-17 06:12:47
【问题描述】:

我正在尝试创建一个类来列出有关汽车的信息。我下面的两个文件是 CarClass.Java 和 Car.java。

运行 CarClass.Java 时,我在“Car car1 = new Car(2018, "Black", "Chevy", "Corvette", 250);" 上收到一个错误一行代码。

错误:类 Car 中的构造函数 Car 不能应用于给定类型;

必需:无参数

找到:int,String,String,String,int

原因:实际参数列表和形式参数列表的长度不同

1 个错误

我的问题是我需要进行哪些更改才能修复此错误,以便我的程序能够正常运行?

 import java.io.PrintStream;

public class CarClass
{
   public static void main(String[] args)
   {
      Car car1 = new Car(2018, "Black", "Chevy", "Corvette", 250);


      System.out.println("The " + car1.getYear() + " " + car1.getColor() + " " + car1.getMake() + " " + car1.getModel() + "Top speed is " + car1.getSpeed() + 
      " mph.");
      }
     }



--------------------------------------------------------------------------------

public class Car
{
   private int carYear;
   private String carColor;
   private String carMake;
   private String carModel;
   private int carSpeed;

   public void Car(int year, String color, String make, String model, int speed)
   {


      this.carYear = year;
      this.carColor = color;
      this.carMake = make;
      this.carModel = model;
      this.carSpeed = speed;
   }

   public int getYear()
   {
   return this.carYear;
   }

   public String getColor()
   {
   return this.carColor;
   }

   public String getMake()
   {
   return this.carMake;
   }

   public String getModel()
   {
   return this.carModel;
   }

   public int getSpeed()
   {
   return this.carSpeed;
   }
 }

【问题讨论】:

    标签: java class constructor


    【解决方案1】:

    您的构造函数不能有返回类型。将其更改为:

    public Car(int year, String color, String make, String model, int speed) {
    
    }
    

    【讨论】:

      【解决方案2】:

      下面的语句会调用类的构造函数:

      Car car1 = new Car(2018, "Black", "Chevy", "Corvette", 250);

      但是既然你在 Car 类中提到了一个返回类型,它将被 JVM 视为一种方法

      public void Car(int year, String color, String make, String model, int speed) {

        this.carYear = year;
        this.carColor = color;
        this.carMake = make;
        this.carModel = model;
        this.carSpeed = speed;
      

      }

      去掉返回类型解决错误!

      【讨论】:

        【解决方案3】:

        您不应在构造函数中使用 return 语句。构造函数用于初始化您的对象。所以,你不需要返回任何东西。因此,下面的修改应该可以工作。

        public Car(int year, String color, String make, String model, int speed)
        {
          this.carYear = year;
          this.carColor = color;
          this.carMake = make;
          this.carModel = model;
          this.carSpeed = speed;
        }
        

        【讨论】:

          猜你喜欢
          • 2015-10-11
          • 2011-04-16
          • 1970-01-01
          • 1970-01-01
          • 2021-11-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-26
          相关资源
          最近更新 更多