Search code examples
javaabstract-class

What is the point of using abstract methods?


What's the point of using "abstract methods"? An abstract class cannot be instantiated, but what about the abstract methods? Are they just here to say "you have to implement me", and if we forget them, the compiler throws an error?

Does it mean something else? I also read something about "we don't have to rewrite the same code", but in the abstract class, we only "declare" the abstract method, so we will have to rewrite the code in the child class.

Can you help me understand it a bit more? I checked the other topics about "abstract class/methods" but I didn't find an answer.


Solution

  • Besides the reminder that you have to implement it, the big advantage is that anyone who references the object by its abstract class type (including this in the abstract class itself) can use the method.

    For instance, let's say we have a class responsible for taking state and manipulating it in some way. The abstract class is going to be responsible for getting the input, converting it to a long (for instance) and combining that value with the previous value in some way -- that "some way" is the abstract method. The abstract class may look something like:

    public abstract class StateAccumulator {
        protected abstract long accumulate(long oldState, long newState);
    
        public handleInput(SomeInputObject input) {
            long inputLong = input.getLong();
            state = accumulate(state, inputLong);
        }
    
        private long state = SOME_INITIAL_STATE;
    }
    

    Now you can define an addition accumulator:

    public class AdditionAccumulator extends StateAccumulator {
        @Override
        protected long accumulate(long oldState, long newState) {
            return oldState + newState;
        }
    }
    

    Without that abstract method, the base class would have no way to say "handle this state somehow." We don't want to provide a default implementation in the base class, though, because it wouldn't mean much -- how do you define a default implementation for "someone else will implement this"?

    Note that there's more than one way to skin a cat. The strategy pattern would involve declaring an interface that declares the accumulate pattern, and passing an instance of that interface to the no-longer-abstract base class. In lingo terms, that's using composition instead of inheritance (you've composed an addition aggregator out of two objects, an aggregator and an adder).