abstract compareTo method not being overrided
Asked Answered
I

3

7

When compiling the code below, I get the following error:

PersonalInformation is not abstract and does not override abstract method compareTo(Object) in Comparable

I assume that means I have a problem with my compareTo method. But everything seems to be all right. Anyone have a suggestion?

import java.util.*;
public class PersonalInformation implements Comparable
{
private String givenName;
private String middleInitial;
private String surname;
private String gender;
private String emailAddress;
private String nationalId;
private String telephoneNum;
private String birthday;

public PersonalInformation(String gN, String mI, 
        String sur, String gen, String eMa, String natId,
        String teleNum, String birthd)

{
        givenName = gN;
        middleInitial = mI;
        surname = sur;
        gender = gen;
        emailAddress = eMa;
        nationalId = natId;
        telephoneNum = teleNum;
        birthday = birthd;


}


public int compareTo(PersonalInformation pi)
{
 return (this.gender).compareTo(pi.gender);
}

}
Incapacity answered 20/2, 2012 at 14:21 Comment(0)
M
21

Do this:

public int compareTo(Object pi) {
    return ((PersonalInformation )(this.gender)).compareTo(((PersonalInformation ) pi).gender);
}

or better

public class PersonalInformation implements Comparable<PersonalInformation>

If you implement the Comparable Interface you have to implement it either for all Objects using the first method or type your class the second way.

Mielke answered 20/2, 2012 at 14:23 Comment(0)
S
6

See juergen d's answer, much better.

You're overloading the method:

public int compareTo(PersonalInformation pi)
{
    return (this.gender).compareTo(pi.gender);
}

instead of overriding it:

public int compareTo(Object pi)

It could be something like:

public int compareTo(Object pi)
{
    if ( ! pi instanceof PersonalInformation )
        return false;
    return (this.gender).compareTo( (PersonalInformation)pi.gender );
}
Sills answered 20/2, 2012 at 14:23 Comment(1)
I think it's called overloading, not overriding.Noumenon
F
6

You need to implement Comparable<PersonalInformation> rather than Comparable for your class to compile and work.

If you are implementing Comparable, the expected method signature is compareTo(Object o) which is missing in your class and hence the error.

Feeley answered 20/2, 2012 at 14:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.