簡體   English   中英

我如何從另一個班級收到實例?

[英]How can I receive instance from another class?

我有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

如何接收“ Human或“ Student ”類的實例age 我現在有這樣的感覺:

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

如您所知,我有此錯誤:

getAge無法解析或不是字段

您可以采取哪些措施解決此問題:

首先,您擁有只能在其類內部訪問的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();
    }         
}

您的小組課程還需要其他內容。 因為如果這是可比較的-您比較的是群體,而不是學生。 以及您的操作方式(我的意思是像第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 .....
    }
}

快樂黑客:)

檢查是否為Human類中的age屬性添加了get方法,並在compareTo方法中從o.getAge更改為o.getAge();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM