Java: extending a class and implementing an interf

2019-03-14 19:38发布

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"):

public class A {
    int doSomthing(int x) {
        return x;
    }
}

public interface B {
    int doSomthing(int x);
}

public class C extends A implements B {

    //trying to override doSomthing...

    int doSomthing(int x) {
        return doSomthingElse(x);
    }
}

Assuming I am allowed to change neither A nor B, my question is can I somehow define C in such a way that it will inherit from both A and B (suppose that it is required for some framework that C will be both an instance of A and B).

Or if not, how would you work around this?

Thanks!

4条回答
时光不老,我们不散
2楼-- · 2019-03-14 20:07

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) {
    // ...
}
查看更多
成全新的幸福
3楼-- · 2019-03-14 20:21

make the method public

public class C extends A implements B {

    //trying to override doSomthing...

    public int myMethod(int x) {
        return doSomthingElse(x);
    }
}

interface methods are always public

or just use composition instead of inheritance

查看更多
小情绪 Triste *
4楼-- · 2019-03-14 20:28

This has to do with visibility. You are using default (no modifier) visibility in C for myMethod but it needs to be public according to the interface B.

Now you might think you used the default visibility for all of them, since in neither A, B, nor C did you explicitly select one of public, private, or protected. However, the interface uses public whether or not you explicitly indicate so.

查看更多
神经病院院长
5楼-- · 2019-03-14 20:34

Simply making the method public when overriding it in C will do.

查看更多
登录 后发表回答