鉴于:

class PhysicsClass {
    private PhysicsInstructor instructor;
    private Set<PhysicsStudent> students;
}

class ChemistryClass {
    private ChemistryInstructor instructor;
    private Set<ChemistryStudent> students;
}

class MathemeticsClass {
    private MathemeticsInstructor instructor;
    private Set<MathemeticsStudent> students;
}


是否可以将所有这些类收集在一个通用类中,例如:

class ScienceClass<T> {
    // What to write here?
    // What to write here?
}


如果这不可能,那么如何防止此处的代码重复?

我想像这样:

class ScienceClass<T extends Instructor, S extends Student> {
    private T instructor;
    private Set<S> students;
}


但这会让我做类似的事情:

ScienceClass<PhysicsInstructor, ChemistryStudent> scienceClass;


这是不正确的。

最佳答案

从主题界面开始

public interface Subject {}

public interface Physics extends Subject {}
public interface Chemistry extends Subject {}
public interface Mathematics extends Subject {}


下一个

public class Instructor<T extends Subject> {
  ...
}


然后,您可以为“班级”只创建一个班级

public class SchoolClass<T extends Subject> {
  Instructor<T> prof;
  ArrayList<Student<T>> students;
}

10-08 03:28