你可以做些什么来解决这个问题:
首先,您有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 .....
}
}
快乐黑客:)