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

后端 未结 9 1355
一整个雨季
一整个雨季 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:51

    Well assume that you don't care whether the methods of the abstract class are implemented or abstract, but by design it has to be abstract so that when someone extends it, they have to add more methods or override the existing ones or use as is. If they don't want to override the methods then the default behavior is already provided in that abstract class.

    In this abstract class, the only criteria you enforce is - one simply cannot instantiate that class and they have to have their only version of class before using it.

    So in general, abstract class with few or all methods being implemented, is much better than having an interface which has no methods implemented at all. This is based on the assumption that you are using it as a single inheritance.

    0 讨论(0)
  • 2021-01-02 21:52

    It can be useful if you consider it an utility class.

    0 讨论(0)
  • 2021-01-02 21:54

    Consider something similar to the NVI pattern (not sure what you'd call it in Java):

    public abstract class A {
        public final void doSomething() {
            System.out.println("required");
            doOptional();
        }
    
        protected void doOptional() {
            System.out.println("optional");
        }
    }
    
    public class B extends A {
        @Override
        protected void doOptional() {
            System.out.println("overridden");
        }
    }
    

    For your public API, you only expose a public final method which cannot be overridden. It performs some required work inside there and an optional method. When extending this class, you can only override doOptional().

    Calling B.doSomething() will always print "required" before it proceeds.

    Since doOptional() is not abstract, there's no purely code reason that class A needs to be abstract. But it might be desired for your particular project. For example, a base service that is always extended into specific sub-projects.

    0 讨论(0)
提交回复
热议问题