Java - implementing multiple interfaces with same method and different return types

前端 未结 1 1715
无人及你
无人及你 2021-01-01 03:32

Consider the following code:

public interface A {
  public A another();
}

public interface B {
  public B another();
}

public interface AB extends A,B {
           


        
相关标签:
1条回答
  • 2021-01-01 03:52

    This error message appears for pre 1.5 versions of Java (at least I can reproduce the error when setting the compliance level to 1.4 in Eclipse). In other words, make sure you're looking at old-enough specs.

    On Java >= 1.5 the following compiles fine.

    interface A {
        public A another();
    }
    
    interface B {
        public B another();
    }
    
    interface AB extends A,B {
        public AB another();
    }
    

    As you say, since AB is both an A and a B, it satisfies both interfaces.


    Here's a quote from the Java Language Specification (Second Edition, i.e. Java 1.4):

    9.2 Interface Members

    The members of an interface are:

    • Those members declared in the interface.
    • Those members inherited from direct superinterfaces.
    • If an interface has no direct superinterfaces, [...]

    It follows that it is a compile-time error if the interface declares a method with the same signature and different return type or incompatible throws clause.

    Further more, the current spec says the following:

    9.4.2 Overloading

    If two methods of an interface (whether both declared in the same interface, or both inherited by an interface, or one declared and one inherited) have the same name but different signatures that are not override-equivalent (§8.4.2), then the method name is said to be overloaded. This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name but different signatures that are not override-equivalent.

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