[英]How can I receive instance from another class?
I have public class Human
, where located instance private int age;
我有public class Human
,在这里实例private int age;
Also, I have public class Student extends Human
, which accordingly inherits Human
. 另外,我有一个public class Student extends Human
,因此继承了Human
。 Also, I have class Group
. 另外,我有类Group
。
public class Group implements Comparable<Group> {
private Student[] group = new Student[10];
}
I want to sort students by age private int age
. 我想给学生按年龄排序private int age
。
How can I receieve the instance age
of the class Human
or Student
? 如何接收“ Human
或“ Student
”类的实例age
? 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 getAge无法解析或不是字段
What you could do to fix this: 您可以采取哪些措施解决此问题:
First, you have private
field which is accessible only inside its class. 首先,您拥有只能在其类内部访问的private
字段。 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. 我在学生类中添加了implements Comparable<Student>
,因为您提到要按年龄比较学生。 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 :) 以及您的操作方式(我的意思是像第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 :) 快乐黑客:)
检查是否为Human类中的age属性添加了get方法,并在compareTo方法中从o.getAge更改为o.getAge();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.