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

时间:2017-01-19 07:00:10

标签: java object constructor

我正在为数据结构项目实施各种数据库,而且我很难绕过我需要做的事情的逻辑。

我有一个名为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感觉有点奇怪。谢谢!

2 个答案:

答案 0 :(得分: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);
    }
}

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

答案 1 :(得分:1)

如果您只需要方向:寻找设计模式"工厂"。这应该对你有帮助。