我正在做一個關於實現接口的家庭作業任務,並且有點迷路。我需要實現可比較的接口並使用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