Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force derived class to call super class method at multiple layers?

I am trying to find the most elegant way to allow a child and parent to react to an event initiated by the grandparent. Here's a naive solution to this:

abstract class A {
    final public void foo() {
        // Some stuff here
        onFoo();
    }

    protected abstract void onFoo();
}

abstract class B extends A {
    @Override
    final protected void onFoo() {
        // More stuff here
        onOnFoo();
    }

    protected abstract void onOnFoo();
}

class C extends B {
    @Override
    protected void onOnFoo() {
        // Even more stuff here
    }
}

So basically, I'm trying to find the best way to allow all related classes to perform some logic when foo() is called. For stability and simplicity purposes I prefer if it is all done in order, although it's not a requirement.

One other solution I found involves storing all the event handlers as some form of Runnable:

abstract class A {
    private ArrayList<Runnable> fooHandlers = new ArrayList<>();

    final public void foo() {
        // Some stuff here
        for(Runnable handler : fooHandlers) handler.run();
    }

    final protected void addFooHandler(Runnable handler) {
        fooHandlers.add(handler);
    }
}

abstract class B extends A {
    public B() {
        addFooHandler(this::onFoo);
    }

    private void onFoo() {
        // Stuff
    }
}

class C extends B {
    public C() {
        addFooHandler(this::onFoo);
    }

    private void onFoo() {
        // More stuff
    }
}

This method is certainly preferable to the first. However I am still curious if there is a better option.

like image 960
BanePig Avatar asked Aug 01 '19 00:08

BanePig


People also ask

How do you call the super class method in subclass?

Subclass methods can call superclass methods if both methods have the same name. From the subclass, reference the method name and superclass name with the @ symbol.

Can a subclass object call a superclass method?

Yes, you can call the methods of the superclass from static methods of the subclass (using the object of subclass or the object of the superclass).

Can subclass access superclass methods?

Does a subclass have access to the members of a superclass? No, a superclass has no knowledge of its subclasses.


1 Answers

Have you considered the Template Method pattern? It works well to define a high level method that delegates to derived types to fill-in the gaps.

like image 142
David Osborne Avatar answered Oct 19 '22 01:10

David Osborne