Mitch Weaver Mitch Weaver - 6 months ago 10
Java Question

Partial implementation of an abstract method?

For example, I have many classes that all need a certain method.
In this method, all these classes need one line of code, the remainder of the method is different.

How could I achieve something like this:

void method(){
everybodyDoesThisStuff;

// more individual stuff

// more individual stuff
}


Abstract methods cannot have a body, and if you were not to make it abstract you would then override the method and lose it.

Answer

You should make the method that does the "more individual stuff" abstract, not the method itself.

// AbstractBase.java
public abstract class AbstractBase {
    public final void method() {
        everybodyDoesThisStuff();
        doIndividualStuff();
    }

    abstract void doIndividualStuff();

    private void everybodyDoesThisStuff() {
        // stuff that everybody does
    }
}

// ConcreteClass.java
public class ConcreteClass extends AbstractBase {
    void doIndividualStuff() {
         // do my individual stuff
    }
}