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

rapt picture rapt · Oct 14, 2011 · Viewed 71.5k times · Source

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!

Answer

ratchet freak picture ratchet freak · Oct 14, 2011

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