java - 当类具有多个不同的字段时,如何对其进行泛化?

标签 java oop generics

给定:

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> {
  ...
}

然后,您可以只为您的“类(class)”创建一个类(class)

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

关于java - 当类具有多个不同的字段时,如何对其进行泛化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43239838/

相关文章:

java - 从字符串Java的值调用函数

python - OOP tkinter : How to set focus (and add text) to entry?

Javascript从父类中定义的继承类方法访问类变量

generics - CaSTLe Windsor Ioc 解析 web.config 中的通用类

java - 进度对话框异步任务参数字符串[]

java - 在单击电子邮件之前发送显示附件图标的电子邮件中的内嵌图像?

Java SSL 重新协商(从 SSL 到清除 channel )

oop - Go 的接口(interface)编程模型与 OOP 相比如何?

Java/Kotlin 通用列表与通配符不兼容的类型

delphi - 泛型、多态性、接口(interface) : what is the solution?