Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, how to inherit methods from abstract class

I have an abstract class Person and and interface comparable, which is also used for some other part of the program. Currently I have a method compareTo() in Person. When I try to compile, I get :

The type Student must implement the inherited abstract method 
 Comparable<Person>.compareTo(Person, Person)

What exactly do I have to do? I don't wont to implement this method in any of the subclasses, because I need this method for all of them, Student, Tutor, Professor, etc... Is there a better way of doing this?

Interface:

interface Comparable<Element> {
    public int compareTo(Element nodeA, Element nodeB);
}

Abstract class Person:

abstract class Person implements Comparable<Person> {

    protected String name;

    public Person(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setName(String newName) {
        name = newName;
    }
    public String toString() {
        return name;
    }

    public int compareTo(Person personB) {
        int comp = this.name.compareTo(personB.getName());
        return comp;
    }
}

And class Student

class Student extends Person implements Comparable<Person> {

    private int id;

    public Student(String name, int id) {
        super(name);
        this.id = id;
    }

    public int getID() {
        return id;
    }

    public void setID(int newID) {
        id = newID;
    }

    public String toString() {
        return id + ", " + name;
    }
}
like image 642
vedran Avatar asked Feb 02 '26 05:02

vedran


2 Answers

Change your interface from:

interface Comparable<Element> 
{     
   public int compareTo(Element nodeA, Element nodeB); 
}

to:

interface Comparable<Element> 
{     
   public int compareTo(Element nodeA); 
}

And make your Person class be defined as:

abstract class Person implements Comparable<? extends Person> { /* ... */ }

And make your Student (and other Person-subclasses be):

class Student extends Person { /* ... */ }

That is all.

like image 82
Kevin Carrasco Avatar answered Feb 04 '26 00:02

Kevin Carrasco


Your Comparable interface has a method compareTo(Element nodeA, Element nodeB). This method is not defined in Student, and it's not defined in Person either. Person has the following method:

public int compareTo(Person personB)

, which doesn't override compareTo(Person nodeA, Person nodeB)

Why are you redefining the standard java.util.Comparable interface?

like image 26
JB Nizet Avatar answered Feb 03 '26 23:02

JB Nizet



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!