BaseFoo cannot be inherited with different arguments: > and >

后端 未结 1 1213
有刺的猬
有刺的猬 2021-01-14 16:48

This is a simplified version of Java inherited Fluent method return type in multiple level hierarchies.

Given the following code:

public enum X {
            


        
相关标签:
1条回答
  • 2021-01-14 17:27

    A class or interface cannot implement or extend from different instantiation of a generic interface. Your Bar interface is breaking this rule. Let's examine the interface declaration:

    static interface Bar<T> extends BaseBar<T, Bar<T>>, Foo<T>
    

    So, Bar<T> extends two interfaces:

    • BaseBar<T, Bar<T>>
    • Foo<T>

    In addition to that, those two interfaces extend from different instantiation of the same interface BaseFoo.

    • BaseBar<T, S extends BaseBar<T, S>> extends BaseFoo<T, S>
    • Foo<T> extends BaseFoo<T, Foo<T>>

    Those inherited interfaces are eventually also the super interfaces of Bar interface. Thus your Bar interface tries to extend from 2 different instantiation of BaseFoo, which is illegal. Let's understand the reason using a simple example:

    // Suppose this was allowed
    class Demo implements Comparable<Demo> , Comparable<String> {
        public int compareTo(Demo arg)     { ... } 
        public int compareTo(String arg) { ... } 
    }
    

    then after type erasure, compiler would generate 2 bridge methods, for both the generic method. The class is translated to:

    class Demo implements Comparable<Demo> , Comparable<String> {
        public int compareTo(Demo arg)     { ... } 
        public int compareTo(String arg) { ... } 
    
        // Bridge method added by compiler
        public int compareTo(Object arg)     { ... } 
        public int compareTo(Object arg) { ... } 
    }
    

    So, that results in creation of duplicates bridge method in the class. That is why it is not allowed.

    0 讨论(0)
提交回复
热议问题