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

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

    It has a conceptual meaning: this class has a behaviour which makes no sense on its own.

    Granted, it's difficult to imagine such a scenario without well-defined extension points (i.e. abstract methods), but occasionally it will be a reasonably accurate model of your problem.

    You can have something like this:

    public abstract class ObjectWithId {
        private final String id;
    
        public ObjectWithId( String id ) {
           this.id = id;
        }
    
        public final String getId() {
           return id;
        }
    }
    

    And then you can extend it to declare different types of objects that have ids. Here you have a fully specified and implemented behaviour but no restriction on any other behaviours subclasses may exhibit.

    Note though that a much neater way to model the same thing is to use composition instead of inheritance.

    public final class ObjectWithId {
        private final String id;
        private final T ob;
    
        public ObjectWithId( String id, T ob ) {
           this.id = id;
           this.ob = ob;
        }
    
        public String getId() {
           return id;
        }
    
        public T getObject() {
           return ob;
        }
    }
    

    But before generics were introduced (up to Java version 1.4), this wouldn't have been as elegant and obviously better than the abstract class solution because you'd have had to trade in type safety.

提交回复
热议问题