Question

Assuming three classes, one being a subclass of the other. Each overwrite the parents' method.

public class BaseClass {

    public void doStuff() {
        performBaseTasks();
    }

}

public class MiddleClass extends BaseClass {

    // {BaseClass} Overrides

    public void doStuff() {
        performMiddleTasks();
        super.doStuff();
    }

}

public class FinalClass extends MiddleClass {

    // {BaseClass} Overrides

    public void doStuff() {
        performFinalTasks();
        super.doStuff();
    }

}

When calling new FinalClass().doStuff(), this would lead to a method invokation order as follows:

  1. performFinalTasks();
  2. performMiddleTasks();
  3. performBaseTasks();

I want to bring the perfomFinalTasks() between performMiddleTasks() and performBaseTasks(). How can I do this?

  1. performMiddleTasks();
  2. performFinalTasks();
  3. performBaseTasks();
Was it helpful?

Solution 2

One possible way, if you can make the middle class abstract:

public abstract class MiddleClass extends BaseClass {

    // {BaseClass} Overrides
    public void doStuff() {
        performMiddleTasks();
        doProxyExec();
        super.doStuff();
    }

    public abstract void doProxyExec();
}

You override the proxy method in your subclass:

public class FinalClass extends MiddleClass {

    // {BaseClass} Overrides
    public void doStuff() {
        super.doStuff();
    }

    // {MiddleClass} Overrides
    public void doProxyExec(
        performFinalTasks();
    }
}

A not very polymorphic way of method call chaining, but then again the original design is kind of ... odd.

OTHER TIPS

Write a public method in final class doStuffDifferently() and invoke these methods in that order. I am not sure it's possible to do it via any other tricks in the doStuff() method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top