【问题标题】:Trying to use polymorphism, need some corrections [duplicate]尝试使用多态性,需要一些更正[重复]
【发布时间】:2018-02-05 21:02:15
【问题描述】:

所以我使用超类 Vehicle 和子类 Van。 Van 子类继承了超类的马力、重量和空气动力学特性。我还在 Van 中定义了一个名为 carryweight 的新实例变量。当我尝试运行 TestAcceleration.java 时出现此错误:

java error

代码如下:

车辆超类

public class Vehicle
{
public double horsepower;
public double aerodynamics;
public double weight;

public Vehicle(double hp, double w, double ad)
{
    horsepower = hp;
weight = w; 
aerodynamics = ad;
}

public double getHorsepower()
{
    return horsepower;
}

public double getAerodynamics()
{
    return aerodynamics;
}

public double getWeight()
{
    return weight;
}

public double acceleration()
{
double calcAccel = (100/horsepower)*aerodynamics*weight/100;
double roundAccel = Math.round(calcAccel * 100.0) / 100.0;
return roundAccel;
}
}

VAN 子类

public class Van extends Vehicle
{
public double carryweight;

public Van(double hp, double w, double ad, double cw)
{
super(hp, w, ad, cw);
carryweight = cw;
}

public double getCarryweight()
{
    return carryweight;
}

public double acceleration()
{
double calcAccel = (100/horsepower)*(aerodynamics/2)*weight/100;
double roundAccel = Math.round(calcAccel * 100.0) / 100.0;
return roundAccel;
}
}

测试加速类

public class TestAcceleration
{
public static void main (String[] args)
{

Vehicle car1 = new Van(100, 3500, 0.9, 160.4);

System.out.println(car1.acceleration());

}
}

【问题讨论】:

  • 您好,欢迎来到 StackOverflow!您的问题很可能很快就会被关闭甚至删除。为防止将来发生这种情况,请take the tourtake a look at the help center。特别是make yourself famlilar as to what is regarded as on-topic around here。您可能还想查看this question asking how much research is expected
  • 你的参数不匹配,你的意思可能是super(hp, w, ad);
  • 您的代码甚至不应该编译,因为在 Vehicule 类中找不到具有 4 个参数的构造函数
  • 请理解,这个社区不是由导师帮助您解决超基本问题的编程学校。这个想法是认真研究之前发布的问题。但似乎你没有这样做。你甚至不明白你有一个 compiler 错误。你没有在运行你的课程。屏幕截图(你不应该使用它 - 因为错误消息是 text 并且应该在你的问题中以 text 的形式出现)清楚地告诉你你的源代码的不同部分根本不“匹配”。
  • @Tom 不,实际上他声称他在 running 东西时遇到了这个错误。不幸的是,这个新手仍然处于无法正确传达他的问题的水平。

标签: java


【解决方案1】:

您在子类中调用的super 调用父类的构造函数,在本例中为Vehicle,因此您必须使用它的构造函数的参数,即您键入的3 而不是4。

父类构造函数

public Vehicle(double hp, double w, double ad)

您的代码:

public Van(double hp, double w, double ad, double cw)
{
    super(hp, w, ad, cw); // this is wrong, you should call with only 3 parameters, there is no CW in your parent class. The call should be super(hp, w, ad);
    carryweight = cw;
}

【讨论】:

    【解决方案2】:

    您已将四个参数传递给 Van 子类中的 Vehicle 构造函数。

    super(hp, w, ad, cw);
    

    只需从构造函数中删除 cw 就可以了。

    【讨论】:

      【解决方案3】:

      在你调用的子类的构造函数中:

      super(hp, w, ad, cw);
      

      但是你的超类的构造函数只有三个参数。 删除最后一个参数,您的代码将编译。

      【讨论】:

        猜你喜欢
        • 2016-08-27
        • 1970-01-01
        • 1970-01-01
        • 2012-07-08
        • 2011-08-03
        • 1970-01-01
        • 1970-01-01
        • 2020-12-09
        • 1970-01-01
        相关资源
        最近更新 更多