Trying to use polymorphism, need some corrections

时间:2018-02-05 12:57:27

标签: java

So I am using the superclass Vehicle and subclass Van. The Van subclass inherits horsepower, weight, and aerodynamics from the superclass. I have also defined a new instance variable in Van called carryweight. When I try to run TestAcceleration.java I get this error:

java error

Here is the code:

VEHICLE SUPERCLASS

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 SUBCLASS

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

TESTACCELERATION CLASS

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

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

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

}
}

3 个答案:

答案 0 :(得分:2)

The super you are calling in the subclass calls the constructor of your parent class, in this case Vehicle so you must use the paremeters of it's constructor which are 3 and not 4 as you typed.

Parent class constructor

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

Your code:

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

答案 1 :(得分:0)

You have passed four arguments to Vehicle constructor in Van subclass.

super(hp, w, ad, cw);

Just remove cw from constructor and it will be ok.

答案 2 :(得分:0)

In the constructor of your subclass you call:

super(hp, w, ad, cw);

But the constructor of your superclass has only three arguments. Remove the last argument and your code will compile.