Interface vs Base class

后端 未结 30 2577
甜味超标
甜味超标 2020-11-21 07:34

When should I use an interface and when should I use a base class?

Should it always be an interface if I don\'t want to actually define a base implementation of the

30条回答
  •  长发绾君心
    2020-11-21 07:40

    I've found that a pattern of Interface > Abstract > Concrete works in the following use-case:

    1.  You have a general interface (eg IPet)
    2.  You have a implementation that is less general (eg Mammal)
    3.  You have many concrete members (eg Cat, Dog, Ape)
    

    The abstract class defines default shared attributes of the concrete classes, yet enforces the interface. For example:

    public interface IPet{
    
        public boolean hasHair();
    
        public boolean walksUprights();
    
        public boolean hasNipples();
    }
    

    Now, since all mammals have hair and nipples (AFAIK, I'm not a zoologist), we can roll this into the abstract base class

    public abstract class Mammal() implements IPet{
    
         @override
         public walksUpright(){
             throw new NotSupportedException("Walks Upright not implemented");
         }
    
         @override
         public hasNipples(){return true}
    
         @override
         public hasHair(){return true}
    

    And then the concrete classes merely define that they walk upright.

    public class Ape extends Mammal(){
    
        @override
        public walksUpright(return true)
    }
    
    public class Catextends Mammal(){
    
        @override
        public walksUpright(return false)
    }
    

    This design is nice when there are lots of concrete classes, and you don't want to maintain boilerplate just to program to an interface. If new methods were added to the interface, it would break all of the resulting classes, so you are still getting the advantages of the interface approach.

    In this case, the abstract could just as well be concrete; however, the abstract designation helps to emphasize that this pattern is being employed.

提交回复
热议问题