我如何从另一个班级收到实例?

时间:2018-12-03 20:17:45

标签: java

我有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对学生进行排序。

如何接收类ageHuman的实例Student?我现在有点这样:

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

如您所知,我有此错误:

  

getAge无法解析或不是字段

2 个答案:

答案 0 :(得分: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 .....
    }
}

Happy Hacking :)

答案 1 :(得分:0)

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