Search code examples
javagenericsinheritanceoverridingfunctional-interface

In Java, how to let child class decide of which type parameter class use as overridden method argument?


I have an abstract class in which I want to have an abstract method taking in argument a Consumer functional interface and let the child class decide which type should parameterize the consumer.

I tried it that way:

public void show(Consumer<?> validationHandler) {
    this.validationHandler = validationHandler;
    stage.show();
}

But in the child class, it says that it isn't a correct override:

@Override
public void show(Consumer<Protection> validationHandler) {
    super.show(validationHandler);
}

My goal is to be able to call this method on a child instance and having the correct type provided in my consumer lambda that I will pass.

Do you have any idea how to proceed?


Solution

  • Make your base class generic (with generic type T), and make show() accept a Consumer<T> (or a Consumer<? super T>. Make the subclass extend BaseClass<Protection>.

    class BaseClass<T> {
        public void show(Consumer<T> validationHandler) { //  or Consumer<? super T>
        }
    }
    
    class SubClass extends BaseClass<Protection> {
        @Override
        public void show(Consumer<Protection> validationHandler) { //  or Consumer<? super Protection>
            super.show(validationHandler);
        }
    }
    
    class Protection {}