What's the point in having an abstract class with no abstract methods?

后端 未结 9 1514
一整个雨季
一整个雨季 2021-01-02 21:11

Can have an abstract class implementing all of its methods-- with no abstract methods in it.

Eg.:

public abstract class someClass          


        
9条回答
  •  难免孤独
    2021-01-02 21:47

    This can be useful for cases when the classes derived from the abstract base class must have some behaviour that is different from each other but that behaviour can not be abstracted as residing within a method that has the same signature for all the classes. Being unable to share a signature can occur if the different behaviour requires methods that are passed different primitive types. Because they use primitive types you can not use generics to express the similarity.

    An abstract base class without any abstract methods is acting a bit like a marker interface, in that it is declaring that implementing classes must provide some behaviour without having that behaviour encapsulated within a new method with a signature that is the same for all implementations. You would use an abstract base class rather than a marker interface when the implementing classes have some behaviour in common, especially if the base class can implement it for the derived classes.

    For example:

    abstract class Sender {
       protected final void beginMessage() {
          ...
       }
    
       protected final void endMessage() {
          ...
       }
    
       protected final void appendToMessage(int x) {
          ...
       }
     }
    
     final class LongSender extends Sender {
        public void send(int a, int b, int c) {
           beginMessage();
           appendToMessage(a);
           appendToMessage(b);
           appendToMessage(c);
           endMessage();
        }
     }
    
     final class ShortSender extends Sender {
        public void send(int a) {
           beginMessage();
           appendToMessage(a);
           endMessage();
        }
     }
    

提交回复
热议问题