I am working on a homework assignment on implementing interfaces, and am a little lost. I need to implement the comparable interface and use the compareTo() method. Here is the code of my super class, it has three subclasses that are all different forms of vehicles. In this case I am trying to campare the number of doors that they have.
Below is the code for the "Vehicle" superclass
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;
}
}
Currently it is a work in progress, and I'm not to sure where to go from here on the compareTo method. Any help is much appreciated.
Thanks!
Edit Once I get the compareTo() method working in the superclass, is there anything that I need to add to the subclasses to make this function?
Thanks!
You should have Vehicle implement Comparable<Vehicle>
, so your compareTo
method can take a Vehicle
argument rather than having to cast.
But if you're asking how to implement the compareTo
method, then if this vehicle is supposed to be less than the other vehicle, return a negative number; if it's supposed to be greater, return a positive number, and if they're supposed to be equal, return 0
. You'll probably be using color.compareTo(otherVehicle.color)
to compare the colors, since they are String
s.
That should be enough hints!