Why is this type not a valid substitute for the type parameter?

前端 未结 3 620
醉梦人生
醉梦人生 2020-12-28 23:14

I\'m experimenting with using generics to support a configurable structure of delegating objects (decorators, wrappers). I want to build a chain of delegators that implement

3条回答
  •  醉酒成梦
    2020-12-28 23:38

    It looks like this is what you are trying to do.

    static interface Delegator {
        }
    
        static class DelegatorChain, C> {
        }
    
        static interface Foo {
        }
    
        static class FooDelegator implements Delegator, Foo {
        }
    
        public static void main(String[] args) {
            DelegatorChain chain = new DelegatorChain();
        }
    

    Your initial example does not compile because the types are not correct. The Generic type in DelegatorChain is a "FooDelegator" but the generic type required in the Delegator is "Foo". You'll need the extra generic type parameter that i provided in my answer to make it work as you intended.

    You could also leave the constraint off entirely on DelegatorChain i.e. DelegatorChain.

提交回复
热议问题