Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot make non-abstract subclass of abstract superclass?

I have a subclass that declares all of the methods in my abstract superclass, yet it still gives me an error stating that my class isn't abstract. I cannot figure out why this error is getting thrown.

The specific error I'm getting is

PhoneBookEntry.java:1: error: PhoneBookEntry is not abstract and does not override abstract method compareTo(Object) in Comparable

My code in question:

public abstract class PhoneNumber implements Comparable
{
   protected String firstName, lastName;
   protected int number;

   public PhoneNumber(String firstName, String lastName, int number)
   {
      this.firstName = firstName;
      this.lastName = lastName;
      this.number = number;
   }

   public abstract String getLastName();
   public abstract String getFirstName();
   public abstract int getNumber();

   public int compareTo(PhoneNumber other)
   {
      int last = other.lastName.compareTo(lastName);
      int first = other.firstName.compareTo(firstName);
      int num = other.number - number;
      if(last > 0)
         return 1;
      else if(last < 0)
         return -1;
      else
         if(first > 0)
            return 1;
         else if(first < 0)
            return -1;
         else
            if(num > 0)
               return 1;
            else if(num < 0)
               return -1;
            else 
               return 0;
   }
}

And my subclass:

public class PhoneBookEntry extends PhoneNumber
{
   public PhoneBookEntry(String firstName, String lastName, int number)
   {
      super(firstName, lastName, number);
   }

    public String getLastName()
   {
      return lastName;
   }
   public String getFirstName()
   {
      return firstName;
   }
   public int getNumber()
   {
      return number;
   }

   public int compareTo(PhoneNumber other)
   {
      super.compareTo(other);
   }

}
like image 385
user3010825 Avatar asked Jan 17 '26 21:01

user3010825


1 Answers

This is the problem:

public int compareTo(PhoneNumber other)
{
   super.compareTo(other);
}

You've specified that you're just implementing the raw type Comparable, which has a method with a signature of:

int compareTo(Object)

The cleanest fix for this is to change the declaration of PhoneNumber to:

public abstract class PhoneNumber implements Comparable<PhoneNumber>

You could implement compareTo(Object) instead, but do you really want to be able to compare a phone number with any other object? It makes more sense (IMO) to just claim to be able to compare a phone number with other phone numbers.

like image 125
Jon Skeet Avatar answered Jan 19 '26 20:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!