I have public class Human
, where located instance private int age;
Also, I have public class Student extends Human
, which accordingly inherits Human
. Also, I have class Group
.
public class Group implements Comparable<Group> {
private Student[] group = new Student[10];
}
I want to sort students by age private int age
.
How can I receieve the instance age
of the class Human
or Student
? I have smth like that now:
@Override
public int compareTo(Group o) {
return o.getAge - this.getAge;
}
As you can realize, I have this error:
getAge cannot be resolved or is not a field
What you could do to fix this:
First, you have private
field which is accessible only inside its class. In your case, you could add public methods to get/set value to make it accessible to the outside world.
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;
}
}
I added implements Comparable<Student>
to the Student class because you mention you want to compare students by age. Also, check comments :
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();
}
}
And your Group class needs something else. Because if this one is comparable - you compare groups, not students. And how you do it (I mean the rules like when group 1 is equal to group 2 and when it is less than group 2 etc.) - it's all up to you :)
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 :)
检查是否为Human类中的age属性添加了get方法,并在compareTo方法中从o.getAge更改为o.getAge();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.