我问的是一个非常基本的问题,它可能被标记为重复(虽然我找不到答案):
Is there any practical example of an Abstract Class with all the methods declared as Abstract?
在大多数情况下,也如 Java 教程中所述,具有所有抽象方法的类应该是一个接口(interface)。
但是由于抽象类和接口(interface)是两个不同的概念,我正在寻找一个有说服力的例子来拥有“完整的抽象类”
最佳答案
我认为唯一实用的方法是 Abstract class
可以保持状态。因此,您可以拥有访问级别为 protected
的内部属性,并且您可以制作 protected abstract methods
,在接口(interface)中您不能导致所有都是 public
.
一个实际的例子可能是这样,java中的 protected 方法具有“继承访问”和“包访问”。
public interface Operation{
void operate();
}
public abstract class AbstractClase implements Operation{
protected Operation delegate;
public AbstractClase(Operation delegate){
this.delegate=delegate;
}
//delegate implementation responsability to children
protected abstract doSomething();
}
使用抽象类的缺点是你也失去了扩展其他东西的可能性。
关于java - 具有所有抽象方法的抽象类 - 实际示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17159781/