Since Java has nominal typing, so org.theirs.Foo nothing to do with org.yours.Foo , even if they have exact exact method signatures, I donβt think it can be done with inheritance in Java. Even with generics, AFAIK cannot say: "This method accepts an instance of Bar<T extends Foo OR Bar> ".
Instead, I think you want to use the adapter interface for the Foo library with your own (that is, a FooAdapter , having the same signatures as Foo ), and continue with Bar . Then the methods you want in Bar can be extracted from the FooAdapter . Unfortunately, your code will need to be modified so that wherever you previously referred to Foo , you could either refer to:
Bar , if only the called methods are those that you define in your interfaceFooAdapter if methods defined in Foo are called, but NOT in Bar .
This method, although clean and a good separation of problems, can be painful and tedious to implement, I'm afraid.
An example of how this will work is shown in the following code snippets:
Third party library
package org.theirs; public interface Foo { void doSomething(); void doSomethingExtra(); }
Your code
package org.mine; public interface Bar { void doSomething(); } public class BarImpl implements Bar{ public void doSomething( ); } public class FooAdapter implements Bar{ private final Foo adapted; public FooAdapter(Foo adapted) { this.adapted = adapted; } public void doSomething() { adapted.doSomething();
In this example, you can see that the doSomethingExtra() method is not available from your code since the Bar interface does not specify it.
Other offers
Note that there may be useful tricks that you could do when rewriting classes, for example with AspectJ. I assume that you will prefer the effect you desire at compile time in pure Java.
Another suggestion is to have a Bar implementation that throws an UnsupportedOperationException for Foo methods that you don't need. Although there is a precedent for major Java libraries (such as the UnmodifiableList in the JDK), I would recommend abandoning this practice altogether. However, if the cost of replacing links to their Foo with your new FooAdapter quite high, this can be a good compromise for using this strategy.