我正在做一个关于实现接口的家庭作业任务,并且有点迷路。我需要实现可比较的接口并使用compareTo()方法。这是我的超级班的代码,它有三个子类,都是不同形式的车辆。在这种情况下,我试图宣传他们拥有的门的数量。Java使用可比较的接口
下面是“车辆”的代码超类
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;}
public int compareTo(Object o) {
if (o instanceof Vehicle) {
Vehicle v = (Vehicle)o;
}
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;
}
}
目前,它是一项正在进行的工作,我不知道在哪里可以从这里去compareTo方法。任何帮助深表感谢。
谢谢!
编辑 一旦我得到的compareTo()方法在超类的工作,是有什么我需要添加到子类,使这个功能呢?
谢谢!
谢谢,这是有益的。虽然我仍然不确定如何正确使用这里的compareTo()方法。我不知道如何去比较numberoffDoors int与这些对象 – salxander 2012-04-12 19:19:39
啊!没有看到你的答案的其余部分,谢谢! – salxander 2012-04-12 19:20:21
你可以比较那些老式的方式。 'if(this.numberOfDoors
2012-04-12 19:21:21