0

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Ombrelin
  • 547
  • 1
  • 8
  • 27

1 Answers1

2

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 {}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • i'm wonder why `Consumer super T>`, i gues that also `Consumer extends T>` could be useful... i really wonder what the "Consumer" abstraction is about... i guess the question's author could explain a little bit its purpose... – Victor Dec 14 '19 at 14:24
  • 2
    @Victor https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html, https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super. Consumer extends T> could not be useful. You couldn't do anything with such a consumer. – JB Nizet Dec 14 '19 at 14:29
  • i thought that was a custom abstraction not that one you point @JB Nizet... based on what you assume that? perhaps i'm missing some common "Implicit" voculabulary here – Victor Dec 14 '19 at 15:29
  • 1
    There is a standard Consumer functional interface in the Java library. So when the OP talks about using a Consumer functional interface, it's safe to assume it's the standard one. And even if it wasn't, a Consumer is something that consumes, so it would be similar. – JB Nizet Dec 14 '19 at 15:57
  • okey... probably cuz i'm not use to work with that terms.. to me it is as this: if you will work with objects below the hierharchy you use super, if you gonna work with objects above the hierchachy you employ extends.. i shall re-read more about consumer and producer, guess i forgot then.. – Victor Dec 14 '19 at 16:40