简体   繁体   English

是否有可能覆盖通用功能?

[英]Is it possible to override a generisized function?

Is it possible to override a generisized function as illustrated in the code snippet below? 是否可以覆盖下面的代码片段所示的泛型函数?

interface A {
}

interface B extends A {
}


abstract class C {
    protected abstract <T extends A> void abc(T xyz);
}

class D extends C {
    @Override
protected void abc(B xyz) {
    // doesn't compile
    // The method abc(B) of type D must override or implement a supertype method
    }
}

Thanks 谢谢

With your code, an instance of D is an instance of C , and consequently must accept any subclass of A as an argument to its abc() method. 对于您的代码, D的实例是C的实例,因此必须接受A的任何子类作为其abc()方法的参数。 What you want is an instance which only accepts a specific subclass. 您想要的是一个仅接受特定子类的实例。 You need to generify C (rather than just C#abc() ). 您需要泛化C (而不只是C#abc() )。 Then you can make D extend C<B> , like so: 然后可以使D扩展C<B> ,如下所示:

interface A {
}

interface B extends A {
}

abstract class C<T extends A> {
    protected abstract void abc(T xyz);
}

class D extends C<B> {
    @Override
    protected void abc(B xyz) {
        // Compiles
    }
}

A proof that you can't generify the method only: 不能仅泛化该方法的证明:

interface A {
}

interface B extends A {
    public void def();
}

abstract class C {
    protected abstract <T extends A> void abc(T xyz);
}

class D extends C {
    @Override
    protected void abc(B xyz) {
        xyz.def();
    }

    public static void main(String[] args) {
        D d = new D();
        d.abc(new B(){}); // Invokes def() on a B, OK
        C c = (C) d;      // Cast to a C, OK
        c.abc(new A(){}); // C#abc() applies to an A, but tries to invoke
                          // a's def(), which it lacks
    }
}

您的D类应该扩展C<B>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM