I'm programming with java. Let's say I have an "MyInterface" interface, and a "MyClass" abstract class.
I want to ensure that every class implementing the "MyInterface" interface is inherited from "MyClass". An inherited class开发者_如何学C from MyClass is perfectly able to NOT implement the "MyInterface" interface.
Is this possible ? Thanks. I'm sorry if my english is bad but I'm french.
I want to ensure that every class implementing the "MyInterface" interface is inherited from "MyClass".
Nope. That's not possible. The whole point of an interface is to make it so that classes from different inheritance hierarchies can implement support for a pre-defined set of capabilities.
AFAIK, you can't do this directly.
Generics let you say something like this, if it helps:
public <T extends MyClass & MyInterface> void foo(T param) { /**/ }
So, you can only call foo() with parameters that are both MyClass and MyInterface.
Or, why not have two abstract base classes?
abstract class MyClass { /* stuff here */ }
abstract class MyInterfaceClass extends MyClass { /* empty */ }
Then, use MyInterfaceClass instead of MyInterface.
Or, if you just care about containers, write your own:
static class MyList extends ArrayList<MyInterface> {
@Deprecated
public boolean add(MyInterface obj) {
assert obj instanceof MyClass;
return super.add(obj);
}
public <T extends MyClass & MyInterface> boolean add(T obj) {
return super.add(obj);
}
}
Then, you will get a deprecation warning any time you make a mistake.
But my question remains - what problem are you trying to solve? Can you use more descriptive names instead of "Class" and "Interface"? Perhaps the right solution is something completely different..
No, it is not possible. Any class can implement MyInterface
. There is no way to limit implementors to subclasses of MyClass
.
If you really need a limitation like that I think you'll be stuck with having to not use an interface and instead use MyClass
in place of an interface.
精彩评论