Search code examples
javacomparablecompareto

Comparable and compareto


I have a problem. I have a class that extends another class and implements Comparable. But when I tried to compile my program I had this error: Flight is not abstract and does not override abstract method compareTo. Anyway, the code of Flight is this:

class Flight extends KeyFlight implements Comparable<Flight>{

 public KeyFlight kf;
 public boolean departure;

 public void Flight(){
 KeyFlight kf=new KeyFlight();
 boolean departure=false;
 }

 public int compareTo(KeyFlight other){
  if (kf.time==other.time){
  if (kf.key<other.key){
   return kf.key;
  } else {
   return other.key;
  } 
 } else {
  if (kf.time <other.time){
   return kf.key;
  } else {
   return other.key;
  }  
 }
}
}

Thank you in advance!


Solution

  • You should use

    implements Comparable<KeyFlight>
    

    Instead of

    implements Comparable<Flight>
    

    As you want to compare two keyflights rather than flights itself. The Type of parameter that you defines in compareTo, should match with the type you specified in implements clause that you are going to compare with.

    Another issue with your code is, in your constructor you are re-defining KeyFlight, it should be

    public void Flight(){
        kf=new KeyFlight();
    

    Else you will get NullPointerException in future. Same applies for your departure boolean.

    A side note, By Default in java boolean is initialised to false, so you don't have to explicitly say that in constructor.