Can we use generic to allow only specific types instead of any type ?

后端 未结 3 991
庸人自扰
庸人自扰 2021-01-22 19:49

Suppose I have three isolated public classes (no IS-A relationship) A, B and C. I want to define a field in C such that it\'s type can either be A or B.

Currently I\'m a

3条回答
  •  情书的邮戳
    2021-01-22 20:38

    You can't do that but you can set boundaries on what type you want to accept.

    If you have

    class A extends BaseType {}
    class B extends BaseType {}
    

    you can define the class C to be

    class C { ... }
    

    Either a class or an interface as base type work.

提交回复
热议问题