【发布时间】:2015-06-23 08:32:56
【问题描述】:
我开始学习JAVA。我被要求创建一个跟踪新车和二手车的汽车程序。我应该创建一个名为 car 的超类,两个名为 UsedCar 和 NewCar 的派生类,以及一个测试这 3 个类的 Driver 类。
所有类都编译并运行。然而。当我输出它时,我得到垃圾输出。我不明白我哪里出错了。我知道 Driver 类很好,还有超级“Car”类。在 UsedCar 和 NewCar 类的某个地方,它会导致输出错误。任何意见或建议都会有所帮助。
这是我的驱动程序类:
public class CarDriver
{
public static void main(String[] args)
{
NewCar new1 = new NewCar(8000.33, "silver");
NewCar new2 = new NewCar(8000.33, "silver");
if (new1.equals(new2))
{
new1.display();
}
UsedCar used1 = new UsedCar(2500, 100000);
UsedCar used2 = new UsedCar(2500, 100000);
if (used1.equals(used2))
{
used1.display();
}
} // end main
}//end class
这是我的汽车类:
import java.util.*;
public class Car
{
//Variables
public Double price;
//Constructor
public Car(Double cost)//constructor to create instances of SavingsAccount
{
price = cost *2;
}
//GetPrice method
public Double getPrice()//method to get the cars' price
{
return price;//returns the value of the price
}
}//end class Car
这里是派生类:NewCar
import java.util.*;
public class NewCar extends Car
{
//Variables
public String color = "silver";
NewCar new1 = new NewCar(8000.33, "silver");
NewCar new2 = new NewCar(8000.33, "silver");
//Constructor - Two Parameter
public NewCar (Double price, String color)//constructor to create instances of new car
{
super(price);
color = this.color;
}
//Equals Method
public boolean equals(Car NewCar)
{
if (NewCar == null)
{
return false;
}
else
{
return
price.equals(new1.price) &&
color.equals(new2.color);
}
} // end equals
//Display method
public void display ()
{
System.out.println(" " + new1.price + new1.color);
}//end display method
}//end class NewCar
二手车
import java.util.*;
public class UsedCar extends Car
{
//Variables
private double mileage;
public String color = "silver";
UsedCar used1 = new UsedCar(2500, 100000);
UsedCar used2 = new UsedCar(2500, 100000);
//Constructor -Two Parameter
public UsedCar (double price, double mileage)//constructor to create instances of new car
{
super(price);
mileage = this.mileage;
}
//Equals Method
public boolean equals(Car UsedCar)
{
if (UsedCar == null)
{
return false;
}
else
{
return
price.equals(used1.price) &&
color.equals(used2.color);
}
} // end equals
//Display method
public void display ()
{
System.out.println(" " + used1.price + used1.mileage);
}//end display
}//end class
我无法粘贴我的输出,但它在命令行上看起来像这样并且它会不停地继续:
“在 NewCar .(NewCar.java:11)”
【问题讨论】:
标签: java inheritance equals superclass derived-class