如何更正我的Java代码?

时间:2018-01-30 22:19:42

标签: java

因此,当程序运行时,它会打印:

0.0
0.0
0.0

但是它应该打印在子类中计算的数字。子类继承父类的所有变量。在主方法中声明SportCar的类型以及分配给变量hp,w和ts的数字。这是代码。

public class TestConsumption
{
public static void main (String[] args)
{
    SportCar car1 = new SportCar(200, 1500, 220);
    SportCar car2 = new SportCar(100, 1000, 170);
    SportCar car3 = new SportCar(135, 1100.2, 173);

    System.out.println(car1.computeConsumption());
    System.out.println(car2.computeConsumption());
    System.out.println(car3.computeConsumption());
}
}

THE SUBLASS

public class SportCar extends Vehicle
{
public double topspeed;

public SportCar(double hp, double w, double ts)
{
    super(0.0, 0.0, 0.0);
    topspeed = ts;
    aerodynamics = 0.5;
}

public double getTopspeed()
{
    return topspeed;
}

public double computeConsumption()
{
    double fuelConsumption = (1000+(weight/5))*(topspeed/100)*(aerodynamics*horsepower)/10000;
    return fuelConsumption;
}
}

父母课程

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;
}
}

3 个答案:

答案 0 :(得分:1)

您没有将参数传递给父构造函数,只需忽略它们并放入0.0。

public SportCar(double hp, double w, double ts)
{
    super(0.0, 0.0, 0.0);
    ...
}

public SportCar(double hp, double w, double ts)
{
    super(hp, w, ts);
    ...
}

答案 1 :(得分:0)

将您的参数传递给父构造函数,然后使用getters

获取它们的值

答案 2 :(得分:0)

我相信这是因为你的SuperCar构造函数会自动将马力,空气动力学和重量设置为0。 虽然您确实将空气动力学设置为0.5,但是当您计算燃油消耗量时,您将乘以设定为0的马力,因此您将始终收到0作为答案。 正确的构造函数应该是

`public SuperCar(double hp, double w, double ts){
super(hp, w, 0.5);
topspeed = ts;
}`

作为旁注,您所有的班级数据确实应该是私人的或有时受到保护,但几乎从不公开。