问题
Consider the interfaces
public interface SuperInterface {
public void execute(Map<String,object> argument);
}
public interface SubInterface extends SuperInterface {
public void execute(Argument extra , Map<String,Object> args);
}
Is it possible to completely override SuperInterfaces.execute with SubInterface.execute even though it has different arguments ?
OR
Am I doing it wrong ? What is the right way to design this spec ?
回答1:
Is it possible to completely override SuperInterfaces.execute with SubInterface.execute even though it has different arguments ?
If you are allowed to do this, you will breach an agreement.
Am I doing it wrong ?
Yes, of course.
What is the right way to design this spec ?
You can't disobey an agreement. So, you can't do like this.
回答2:
No. When you override a method, it must have the same number and types of arguments. Currently you are overloading the execute method in SubInterface.
You could, however, call execute(Map<String, Object> args) from execute(Argument extra , Map<String, Object> args) from your implementation of SubInterface.
回答3:
Your SubInterface should be an abstract class.
Then you can have a default and final implementation of one-arg execute which actually calls two-arg execute.
回答4:
i doubt if i understand your question. overriding is redefining method in subclass/interface with the same arguments (or subtype arguments). here you are overloading the methods.
being an interface, it wont allow overriding. bcz overriding is a term related to defination, but interface methods doesn't have one.
回答5:
The best thing you can do is to @Deprecate(d) the method.
e.g.
public interface SuperInterface {
public void execute(Map<String,object> argument);
}
public interface SubInterface extends SuperInterface {
@Deprecated
public void execute(Map<String,object> argument);
public void execute(Argument extra , Map<String,Object> args);
}
This way, you (and others) will be notified about the invalid use of the class method. If you wait for Java8, I think you will be able to create also a default method for the method in the sub interface and throw an exception when someone executes it (of course the implementing class should not implement the method :)
来源:https://stackoverflow.com/questions/15270889/override-disable-super-interface-method