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?

图片转代码服务由CSDN问答提供 功能建议

我有一段代码,其中一些类正在实现一个接口。 < p>感觉是正确的,但是在子类之间有一些重复 - 即3种方法。

因此,这就是使用抽象类的尖叫。 \ n

我的问题是,在以下情况下使用抽象类和接口是否有任何缺点:

  1. 用于实现接口和子类的抽象类 扩展抽象类
  2. 子类以扩展抽象类并实现接口

    \ n

    抽象类和接口是否应该像这样一起使用?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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条)

相关推荐 更多相似问题