假设我有 2 个类,分别为 class Cow
和 class Pig
。
它们都实现了接口(interface) Animal
。
对于接口(interface)
,只有 2 个方法,分别为 public void eat()
和 public void talk()
。
一切都很好。但是,虽然这似乎很好地利用了接口(interface),但我认为如果我需要向此接口(interface)添加方法,实现就会中断,即我需要去实现这些类中的新方法,这打破了“封闭-开放原则”。
所以我想到,除了interface
之外,我还会使用abstract
类,如果需要添加新方法的话)在未来。
例如,public class Cow extends ...implements Animal
。
这听起来是一个不错的计划(如果不是,请纠正我)。
但问题是,如果这些类扩展
已经是其他类了怎么办?在这种情况下,我无法扩展 2 个类(class)。
所以我的问题是:
Is there a pattern where I could declare a common
interface
of related classes while withholding the ability to add new methods in the future that doesn't break the "closed-open principle" and doesn't break implementations?
最佳答案
Java 8 有 default methods
public interface Animal {
void eat();
void speak();
default void sleep(){}
}
现在,您的Animal
必须覆盖eat
和speak
,但可以选择覆盖sleep
。
在 Java 8 之前,使用抽象类
是防止必须实现每个接口(interface)
方法的常用方法。正如您所指出的,这不适用于多重继承,因此不能用于解决所有情况。
附注不要声明 interface
方法 public
,这是所有 interface
成员的默认可见性。
关于java - 向类添加方法而不破坏实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24228650/