Java面向对象;创建对象数组

Java OOP; creating array of objects

我想创建一个对象数组,其中 3 个对象来自一个 class,第 4 个来自第二个 class。

在第一个 class 中,我执行了以下操作:

public class Pupil {
        public int n= 0;

        Pupil(int n) {
            this.n = n;} 
}

在第二个 class 中,我做了以下操作:

public class Tutor {
        public int m= 0;

        Tutor(int m) {
            this.m = m;} 
}

在主体class中,我创建了几个学生对象和一个导师对象,像这样:

public class Main {
    public static void main (String[] args) {
        //Pupil(n) while for tutor objects it'd be Tutor(m) 
Pupil pupil1 = new Pupil(9);
Pupil pupil2 = new Pupil(8);
Pupil pupil3 = new Pupil(6); 
Tutor tutor1 = new Tutor(2);

在 main 中使用对象打印效果很好。

但我想创建第四个 class,我将它们分组到对象数组中,但它不会看到我创建的用于从中创建组的对象。我也不确定创建对象数组的格式。

public class Groups {

    public static void main(String [] args){



    Pupil [] g1 = {tutor1, pupil1, pupil2, pupil3};
    //cannot resolve any symbols 
    }
}

编辑:根据我的导师,组 class 应该是静态的来解决这个问题,但我不确定如何实际编码?

Edit2:答案指出数组应该是对象,因为上面的代码只能创建学生数组,不能创建学生和导师对象。

Object [] g1 = {tutor1, pupil1, pupil2, pupil3};

但这仍然没有解决从组中看不到任何对象的主要问题class(//无法解析任何符号)

数组只能包含相同类型的对象。话虽如此,这里有一个方法:

Object[] g1 = {tutor1, pupil1, pupil2, pupil3};

Java 是一种强类型编程语言,因此您不能将不同的类型 objects 添加到同一个集合中。但是你利用了 OPP 多态性原理。您可以创建 parent class 并从 parent class.

扩展您的子 classes

Parent Class

public class Group {
}

Child Classes

public class Pupil extends Group {

    public int m = 0;

    public Pupil(int m) {
        this.m = m;
    }

}
public class Tutor extends Group {

    public int n = 0;

    public Tutor(int n) {
        this.n = n;
    }

}

所以你可以这样使用它:

public class TestSchool {

    public static void main(String[] args) {
        Pupil pupil1 = new Pupil(9);
        Pupil pupil2 = new Pupil(8);
        Pupil pupil3 = new Pupil(6);
        Tutor tutor1 = new Tutor(2);
        Tutor tutor2 = new Tutor(2);

        Group[] groupArray = {pupil1, pupil2, pupil3, tutor1, tutor2};
    }
}