Java 用抽象类实现接口

Java 用抽象类实现接口,java,oop,interface,Java,Oop,Interface,我有一个接口。为了回答这个问题,我将把它简化为: interface EraseableColoredPencil { //This method seems appropriate for an interface; //The implementation will change with each class that implements this interface. void draw(); //This method does not seem as appro

我有一个接口。为了回答这个问题,我将把它简化为:

interface EraseableColoredPencil {

  //This method seems appropriate for an interface;
  //The implementation will change with each class that implements this interface.
  void draw();

  //This method does not seem as appropriate;
  //The implementation of the erase method would be the same for all classes.
  void erase();
}
我的问题是:根据OOP原则,表达这一点的最佳方式是什么?两种方法的接口似乎都不合适。以下是我提出的选项:

  • 列出接口上的所有方法,无论实现是否相同。然后使用一个抽象类来实现shared erase()。这似乎是我的最佳解决方案,因为
    ErasableColoredPencil
    需要实现
    erase()
    ,这允许所有类共享相同的实现。我知道这是可能的,但我关心的是它是否遵循最佳实践
  • 消除接口并使用抽象类。这似乎并没有遵循好的设计模式,但可以保证每个扩展类都有适当的方法,甚至有一致的实现,直到覆盖给定的方法为止
  • 照原样走。我可能想得太多了,这真的是个不错的方法
  • 还有别的。我肯定我错过了什么。有更好的方法吗

  • 正如您现在所问的关于Java的问题一样,您还有第三个选项,可用于Java8:

    这允许您使用接口并定义
    擦除
    的默认行为,从而无需使用抽象类:

    interface EraseableColoredPencil {
    
        void draw();
    
        default void erase() { ... }
    }
    
  • 其他事项:遵循以下步骤并拆分界面:

    interface Drawer{
      void draw();
    }
    
    interface Erasable {
      void erase();
    }
    
    interface EraseableDrawer extends Drawer, Erasable {
    }
    
    现在,您只需要依赖于
    Drawer
    Erasable
    ,这取决于您真正需要的方法(或者如果您同时需要这两种方法,则依赖于
    Erasable Drawer

    如果所有或大多数类的
    erase()
    实际上都是相同的实现,那么您仍然可以使用一个抽象类
    AbstractErasableDrawer
    ,该抽象类通过
    erase()
    的具体实现来实现
    ErasableDrawer
    (或使用默认实现)


  • 如果你是从C#的角度来看的话,是的。我在Java和C#中都遇到过这个问题,Java命名约定不需要
    I
    前缀。看吧,为了这个网站,我试图简化这个问题,而实际上这是一个复杂得多的类。这背后的想法是,
    draw()
    方法根据颜色的不同而不同,但在本例中,
    erase()
    方法最终只是从页面中删除颜色。很抱歉,在多种语言中都存在此问题,但我现在删除了标记。