compareTo()
方法来比较车辆上的门数),还有一个类必须实现“混合”类(我不知道这意味着什么)。然后我们必须实现toString()
,equals(Object o)
和compareTo(Object o)
方法。我认为我已经弄清楚了
compareTo()
,但是对于equals()
我一无所知。我们最后要做的是编写一个Main来进行测试,这涉及创建一个Vehicle对象数组,打印它们,对它们进行排序,然后重新打印它们。它还应该遍历数组并打印混合动力汽车的价格溢价,并使用equals(Object o)
方法比较2个车辆。以下是我“Vehicle”超类的代码:
package vehicle;
abstract public class Vehicle implements Comparable {
private String color;
private int numberOfDoors;
// Constructor
/**
* Creates a vehicle with a color and number of doors
* @param aColor The color of the vehicle
* @param aNumberOfDoors The number of doors
*/
public Vehicle(String aColor, int aNumberOfDoors) {
this.color = aColor;
this.numberOfDoors = aNumberOfDoors;
}
// Getters
/**
* Gets the color of the vehicle
* @return The color of the vehicle
*/
public String getColor() {return(this.color);}
/**
* Gets the number of doors the vehicle has
* @return The number of doors the vehicle has
*/
public int getNumberOfDoors() {return(this.numberOfDoors);}
// Setters
/**
* Sets the color of the vehicle
* @param colorSet The color of the vehicle
*/
public void setColor(String colorSet) {this.color = colorSet;}
/**
* Sets the number of doors for the vehicle
* @param numberOfDoorsSet The number of doors to be set to the vehicle
*/
public void setNumberOfDoors(int numberOfDoorsSet) {this.numberOfDoors = numberOfDoorsSet;}
@Override
public int compareTo(Object o) {
if (o instanceof Vehicle) {
Vehicle v = (Vehicle)o;
return this.numberOfDoors - v.getNumberOfDoors();
}
else {
return 0;
}
}
/**
* Returns a short string describing the vehicle
* @return a description of the vehicle
*/
@Override
public String toString() {
String answer = "The car's color is "+this.color
+". The number of doors is"+this.numberOfDoors;
return answer;
}
}
我会同时发布我的一个子类
package vehicle;
abstract public class Convertible extends Vehicle {
private int topSpeed;
// Constructor
/**
* Creates a convertible with a color, number of doors, and top speed
* @param aColor The color of the convertible
* @param aNumberOfDoors The number of doors of the convertible
* @param aTopSpeed The top speed of the convertible
*/
public Convertible (String aColor, int aNumberOfDoors, int aTopSpeed) {
super(aColor, aNumberOfDoors);
this.topSpeed = aTopSpeed;
}
// Getters
/**
* Gets the top speed of the convertible
* @return The top speed of the convertible
*/
public int getTopSpeed() {return(this.topSpeed);}
// Setters
/**
* Sets the top speed of the convertible
* @param topSpeedSet The top speed to set to the convertible
*/
public void setTopSpeed(int topSpeedSet) {this.topSpeed = topSpeedSet;}
/**
* Returns a short description of the convertible
* @return a short description of the convertible
*/
@Override
public String toString() {
String answer = "The car's color is "+super.getColor()
+", the number of doors is "+super.getNumberOfDoors()
+", and the top speed is "+this.topSpeed+" mph.";
return answer;
}
}
我绝对不是要求任何人为我完成工作,但如果有人能更详细地解释接口的工作原理以及这个作业的真正要求,那就太好了。
非常感谢所有的帮助。
谢谢!