简体   繁体   English

在 Java 中,如何让子类决定使用哪种类型的参数类作为重写的方法参数?

[英]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.我的目标是能够在子实例上调用此方法,并在我将传递的消费者 lambda 中提供正确的类型。

Do you have any idea how to proceed?你知道如何进行吗?

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> .使您的基类泛型(具有泛型类型 T),并使show()接受Consumer<T> (或Consumer<? super T> 。使子类扩展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 {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在JAVA中从父类的内部类中调用子类中的重写方法? - How can I call the overridden method in a child class from a parent class's inner class in JAVA? 如何使用类名作为方法参数的类型 - How to use class name as type for method argument 如何使用 class 类型的方法参数? - How to use class type of method parameter? 如何使用抽象类的子类型作为抽象方法的参数类型? - How to use abstract class' child type as the type of an abstract method's parameter? 决定如何根据Java中输入参数的类型执行方法 - Decide how to execute a method based on the type of the input argument in Java Java如何将加载的类参数类型作为泛型参数传递? - Java how to pass a loaded class parameter type as a generic argument? 如何在接受`Base`的重写方法中使用`Derived`类型的参数? - How to use a parameter of type `Derived` in a overridden method accepting `Base`? 限制由少数子类重写的类方法 - restricting a class method overridden by few child classes 我可以从未被子类覆盖的方法内部访问子对象的字段吗? - Can I have access to a field of a child object from inside a method which is not overridden by the child class? 继承规则-覆盖方法的返回类型可以是在覆盖方法中声明的返回类型的子类 - Rule for inheritance — return type of overriding method can be child class of return type declared in overridden method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM