BaseFoo cannot be inherited with different arguments: > and >

后端 未结 1 1226
有刺的猬
有刺的猬 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 extends BaseBar>, Foo
    

    So, Bar extends two interfaces:

    • BaseBar>
    • Foo

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

    • BaseBar> extends BaseFoo
    • Foo extends BaseFoo>

    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 , Comparable {
        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 , Comparable {
        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)
提交回复
热议问题