Then Enok
Then Enok

Reputation: 661

How to force override method and call super at the same time

Ok, so recently I wanted to implement the following

public enum ObjectTypes {
    STRING,
    INTEGER
}

interface IObjectEnhancer{
    void enhance(String s);
    void enhance(Integer i);
    ObjectTypes getLastEnhancedType();
}

class ObjectEnhancer implements IObjectEnhancer{
    ObjectTypes lastUsedType=null;

    @CallSuper
    @Override
    public void enhance(String s) {
        this.lastUsedType=ObjectTypes.STRING;
    }

    @CallSuper
    @Override
    public void enhance(Integer i) {
        this.lastUsedType=ObjectTypes.INTEGER;
    }

    @Override
    final public ObjectTypes getLastEnhancedType() {
        return lastUsedType;
    }
}

class ObjectEnhancerChild extends ObjectEnhancer{
    @Override
    public void enhance(String s) {
        super.enhance(s);
        //child code
    }

    @Override
    public void enhance(Integer i) {
        super.enhance(i);
        //child code
    }
}

And for safety I wanted to add @CallSuper because I really want only the parent to remember the types but I also want the enhance(String) and enhance(Integer) to be abstract so that no clumsy future person (me included) forgets to actually implement these methods.

So below is a method to handle this sort of situation that apparently only I am having and the internet doesn't really have advice on, it might seem stupid to worry about such a small thing but if you have 10+ methods it stars becoming a nightmare(feedback and other solutions welcome):

Upvotes: 0

Views: 72

Answers (1)

Then Enok
Then Enok

Reputation: 661

Just make new abstract methods so that the child is forced to implement them and parent methods call the abstract methods instead of using @CallSuper:

abstract class ObjectEnhancer implements IObjectEnhancer{ //add abstract to parent
    ObjectTypes lastUsedType=null;

    abstract void enhance2(String s); //new
    abstract void enhance2(Integer i); //new

    //removed @CallSuper
    @Override
    final public void enhance(String s) { //changed to final
        this.lastUsedType=ObjectTypes.String;
        enhance2(s); //new
    }

    //removed @CallSuper
    @Override
    final public void enhance(Integer i) { //changed to final
        this.lastUsedType=ObjectTypes.Integer;
        enhance2(i); //new
    }

    @Override
    final public ObjectTypes getLastEnhancedType() {
        return lastUsedType;
    }
}

class ObjectEnhancerChild extends ObjectEnhancer{
    @Override
    public void enhance2(String s) { //changed to abstract method
        //removed super.enhance(s);
        //code
    }

    @Override
    public void enhance2(Integer i) { //changed to abstract method
        //removed super.enhance(i);
        //code
    }
}

Upvotes: 1

Related Questions