0

我有public class Human,位于哪里的实例 private int age; 另外,我有public class Student extends Human,因此继承了Human. 另外,我有课Group

public class Group implements Comparable<Group>  {
    private Student[] group = new Student[10];
}

我想按年龄对学生进行排序 private int age

我怎样才能收到age类的实例HumanStudent?我现在有这样的东西:

@Override
public int compareTo(Group o) {
    return o.getAge - this.getAge;
}

正如你所意识到的,我有这个错误:

getAge 无法解析或不是字段

4

2 回答 2

1

你可以做些什么来解决这个问题:

首先,您有private一个只能在其类内部访问的字段。在您的情况下,您可以添加公共方法来获取/设置值,以使其可供外界访问。

public class Human {
    private int age;

    // public getter to get the value everywhere
    public int getAge() {
        return this.age;
    }

    // setter to set the value for this field
    public void setAge(int age) {
        this.age = age;
    }
}

我添加implements Comparable<Student>到学生类是因为你提到你想按年龄比较学生。另外,检查评论:

public class Student extends Human implements Comparable<Student> {
    // even though it extends Human - Student has no access to private
    // fields of Human class (you can declare it as protected if you want
    // your Student to have access to that field)

    // but protected does not guarantee it will be accessible everywhere!


    // now let's say you want to compare them by age. you can add implements Comparable
    // and override compareTo. getAge() is public and is inherited from the parent
    @Override
    public int compareTo(Student s) {
        return this.getAge() - s.getAge();
    }         
}

而你的 Group 类需要别的东西。因为如果这个具有可比性 - 你比较的是群体,而不是学生。以及你是如何做到的(我的意思是当第 1 组等于第 2 组时以及当它小于第 2 组时等规则) - 这完全取决于你 :)

public class Group implements Comparable<Group>  {
    private Student[] group = new Student[10];

    @Override
    public int compareTo(Group o) {
        // if your Group implements Comparable it means
        // you compare Groups not instances of class Student !
        // so here you need to implement rules for Group comparison !
        return .....
    }
}

快乐黑客:)

于 2018-12-03T21:03:00.103 回答
0

检查是否为 Human 类中的 age 属性添加了 get 方法,并且在 compareTo 方法中从 o.getAge 更改为 o.getAge();

于 2018-12-03T21:00:22.943 回答