我将如何创建一个存储另一个 class 对象的字段?

How would I go about in creating a field in which store object of another class?

所以这里我有一个 class 代表音乐节表演的表演。

public class Act {
    private int num_members;
    private String name;
    private String kind;
    private String stage;


    public Act(int num_members, String name, String kind, String stage) {
        this.num_members = num_members;
        this.name = name;
        this.kind = kind;
        this.stage = stage;
    }

    public Act(int num_members, String name, String kind) {
        this.num_members = num_members;
        this.name = name;
        this.kind = kind;
        stage = null;
    }

    public int getNum_members() {
        return num_members;
    }

    public void setNum_members(int num_members) {
        this.num_members = num_members;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getKind() {
        return kind;
    }

    public void setKind(String kind) {
        this.kind = kind;
    }

    public String getStage() {
        return stage;
    }

    public void setStage(String stage) {
        this.stage = stage;
    }

    public String toString() {
        return "(" + num_members + ", " + name + ", " + kind + ", " + stage + ")";
    }
}

在另一个名为 LineUp 的 class 中,我想在一个名为 acts 的字段中存储最多 30 个行为,并且还有一个方法 addAct 将 Act 作为参数并将其添加到 acts。这是我到目前为止使用的代码,但我不太确定该怎么做。


public class LineUp {
    Act[] acts;


    public LineUp() {
        Act[] acts = new Act[30];
    }

    void addAct(Act a) {

    }
}

如果您使用数组,您必须确保永远不需要添加超过 30 Act 并跟踪数字以帮助您,或者更简单的解决方案是使用 List<Act>因为你不需要用数字来打扰你,只要你喜欢就添加(或删除)

数组:

public class LineUp {
    Act[] acts;
    int number;

    public LineUp() {
        acts = new Act[30]; // you assign to 'this' you don't create a new one
        number = 0; 
    }

    void addAct(Act a) {
        acts[number] = a;
        number++;
    }
}

列表:

public class LineUp {
    List<Act> acts;

    public LineUp() {
        acts = new ArrayList<>;
    }

    void addAct(Act a) {
        acts.add(a);
    }
}