使用类构造函数创建2种不同类型的对象数组

Fue*_*son 2 java constructor object

我正在为数据结构项目实现一个类型的数据库,而且我很难围绕我需要做的事情的逻辑.

我有一个名为的抽象超类,Person它有两个名为Student和的子类Instructor.

最后,我有另一个被调用的类UniversityPeople,它在应用程序使用时创建对两者StudentInstructor对象数组的引用.UniversityPeople调用构造函数时,它使用size作为参数创建指定对象的数组.我似乎无法想到如何在创建时区分构造函数中的两个对象.我的第一个想法是2个构造函数:

Instructor[] instArray;
Student[] stuArray;

public UniversityPeople(int size)
{
    Student[] stuArray = new Student[size];
}
public UniversityPeople(int size)
{
    Instructor[] instArray = new Instructor[size];
}
Run Code Online (Sandbox Code Playgroud)

但在考虑之后(并做了一些阅读)我知道我不能这样做.我的下一个想法是在UniversityPeople构造函数中使用一种对象验证方法,但我很难实现一个.

基本上,类需要知道何时创建Student对象数组以及何时创建Instructor具有整数大小作为参数的对象数组.

如果有人能指出我正确的方向,我会非常感激.我最近一直在用C编码,所以经过这么多时间后,回归OOP感觉有点怪异.谢谢!

Jon*_*eet 5

首先,我会质疑这种方法 - 听起来这个单一的课程试图做太多事情.但是,如果你真的,真的想这样做,我建议调用私有构造函数的静态工厂方法:

public class UniversityPeople {
    private final Student[] students;
    private final Instructor[] instructors;

    private UniversityPeople(int studentCount, int instructorCount) {
        students = new Student[studentCount];
        instructors = new Instructor[instructorCount];
    }

    public static UniversityPeople forStudents(int size) {
        return new UniversityPeople(size, 0);
    }

    public static UniversityPeople forInstructors(int size) {
        return new UniversityPeople(0, size);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以对每个大小执行检查,只有在您真正想要的情况下才会分配大于0.但正如我所说,如果可能,我会重新审视设计.