[英]Add new method to an interface which is directly implemented by many classes
I have a small question on java interfaces 我对java接口有一个小问题
Is there any way to add a new method to java interface without modifying the classes that are implementing it. 有没有办法在不修改实现它的类的情况下向java接口添加新方法。
condition is that I should not introduce new interface 条件是我不应该介绍新的界面
Is there any way to add a new method to java interface without modifying the classes that are implementing it. 有没有办法在不修改实现它的类的情况下向java接口添加新方法。
No. 没有。
condition is that I should not introduce new interface 条件是我不应该介绍新的界面
If the condition also includes not modifying the many classes that directly implement the interface, you have been given an impossible task. 如果条件还包括不修改直接实现接口的许多类,则会给您一个不可能完成的任务。
This is the reason why interfaces are often accompanied by abstract Adapter
classes, that implement all the methods in a do-nothing way. 这就是为什么接口通常伴随着抽象的Adapter
类的原因,它们以无操作的方式实现所有方法。 Implementation classes then extend the adapter rather than implementing the interface, so that if you need to add an interface you only need to modify the interface and the adapter. 实现类然后扩展适配器而不是实现接口,因此如果需要添加接口,则只需要修改接口和适配器。
What you are trying to do is fundamentally impossible. 你想要做的事情从根本上是不可能的。 Unless (as was just pointed out in the comments) you use Java 8. 除非(正如评论中指出的那样)使用Java 8。
Java 8 has introduced a concept of default or defender methods that allow you to add a method to an interface and provide a default implementation of that method within the interface. Java 8引入了默认或防御方法的概念,允许您向接口添加方法并在接口内提供该方法的默认实现。
http://zeroturnaround.com/rebellabs/java-8-explained-default-methods/ http://zeroturnaround.com/rebellabs/java-8-explained-default-methods/
The rest of the answer applies to any version of Java before 8: 其余的答案适用于8之前的任何Java版本:
An interface describes the methods in a class. 接口描述了类中的方法。 If you add a new method to an interface then all classes that implement the interface must implement the method. 如果向接口添加新方法,则实现该接口的所有类都必须实现该方法。 Unless by some stroke of luck the method you are adding already exists in every single implementing class this is just impossible without either adding a new interface or changing the classes. 除非幸运的是,你添加的方法已经存在于每个实现类中,如果不添加新接口或更改类,这是不可能的。
If your interface were an Abstract Class then you could add a stub method that does nothing and allow that to be overridden but interfaces have no concept of optional methods. 如果您的接口是一个抽象类,那么您可以添加一个不执行任何操作的存根方法,并允许覆盖它,但接口没有可选方法的概念。
By using abstract class we can solve this problem. 通过使用抽象类,我们可以解决这个问题。
interface A{
void a();
void b();
}
Class a implement A
Class b implement A ...
if any new method arrive to create an abstract class and add that method into it 如果任何新方法到达创建一个抽象类并将该方法添加到其中
abstract class adapter {
abstract void c();
}
now extend this adapter class for necessary classes.. 现在为必要的类扩展此适配器类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.