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

后端 未结 3 950
庸人自扰
庸人自扰 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条回答
  •  梦毁少年i
    2021-01-22 20:43

    Make the constructor private:

    private C(T param){
    

    And then provide static factory methods to create instances of particular types:

    public static  C create(T param) {
      return new C<>(param);
    }
    
    public static  C create(T param) {
      return new C<>(param);
    }
    

    This doesn't prevent you from using the type C; you just can't create an instance of it.

提交回复
热议问题