douningchang3610 2013-05-20 11:02
浏览 54
已采纳

抽象类和接口在一起?

I have a section of my code where some classes are implementing an interface.

It feels correct, but there is a little duplication among the child classes - namely 3 methods.

So this is screaming out to use an abstract class.

My question is, will there be any cons in using both abstract class and interface in the following situations:

  1. Abstract class to implement the interface and child classes to extend the abstract class
  2. Child classes to extend the abstract class and implement the interface

Or

Should abstract classes and interfaces not be used together at all like this?

  • 写回答

3条回答 默认 最新

  • doutuanxiao4619 2013-05-20 11:04
    关注

    It's perfectly normal to use these two together. Consider for instance AbstractList (implementing List) and AbstractMap (implementing Map) in the JDK.

    My knee-jerk reaction would have been to have the abstract class implement the interface and then have the concrete classes derive from it:

    abstract class Base implements TheInterface {
        /* ...shared methods... */
    }
    
    class Concrete1 extends Base { }
    
    class Concrete1 extends Base { }
    

    But your question raising the other possibility made me think, and I can't see much of an argument against doing it that way:

    abstract class Base {
        /* ...shared methods... */
    }
    
    class Concrete1 extends Base implements TheInterface { }
    
    class Concrete1 extends Base implements TheInterface { }
    

    Further, I can see an argument for doing it that way, specifically that it removes the coupling between the abstract class and the interface. If you have another class that needs the functionality Base provides but doesn't need to implement the interface, you have the flexibility to do that.

    There's also a third option: Composition. You could not have an abstract class at all, but rather have the multiple concrete classes that implement the interface use a common helper class in their implementation:

    class Helper {
        /* ...shared methods... */
    }
    
    class Concrete1 implements TheInterface {
        /* ...uses instance of Helper */
    }
    
    class Concrete1 implements TheInterface {
        /* ...uses instance of Helper */
    }
    

    This has that same flexibility, in another form.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 socket通信实现多人聊天室疑惑
  • ¥15 DEV-C++编译缺失
  • ¥33 找熟练码农写段Pyhthon程序
  • ¥100 怎么让数据库字段自动更新
  • ¥15 antv g6 力导向图布局
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数