Java: extending a class and implementing an interface that have the same method

前端 未结 4 1211
小蘑菇
小蘑菇 2021-02-05 04:39

Probably the following cannot be done (I am getting a compilation error: \"The inherited method A.doSomthing(int) cannot hide the public abstract method in B\"):



        
4条回答
  •  悲&欢浪女
    2021-02-05 05:00

    The method doSomethis() is package-private in class A:

    public class A {
        int doSomthing(int x) { // this is package-private
            return x;
        }
    }
    

    But it is public in the interface B:

    public interface B {
        int doSomthing(int x); // this here is public by default
    }
    

    Compiler is taking the doSomething() inherited by C from A which is package-private as the implementation of the one in B which is public. That's why it's complaining -

    "The inherited method A.doSomthing(int) cannot hide the public abstract method in B"

    Because, while overriding a method you can not narrow down the access level of the method.

    Solution is easy, in class C -

    @Override
    public int doSomthing(int x) {
        // ...
    }
    

提交回复
热议问题