我正在为一个数据结构项目实现一个种类繁多的数据库,我真的很难把我的脑袋围绕着我需要做的逻辑。

我有一个名为Person的抽象超类,它有两个名为StudentInstructor的子类。

最后,我还有一个名为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];
}


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

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

如果有人能指出正确的方向,我将不胜感激。我最近主要是使用C进行编码,因此经过这么长的时间,回到OOP感觉有点奇怪。谢谢!

最佳答案

首先,我会质疑这种方法-听起来这门课正在尝试做太多事情。但是,如果您确实想要这样做,我建议您使用静态工厂方法来调用私有构造函数:

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);
    }
}


您可以针对每个大小执行检查,并且如果确实要大于0,则仅进行分配。但正如我所说,如果可能的话,我会重新设计。

09-16 18:30