Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java通用通配符函数_Java_Generics - Fatal编程技术网

Java通用通配符函数

Java通用通配符函数,java,generics,Java,Generics,当有可能输入子类作为参数时,为什么具有上限的泛型通配符函数不允许访问子类的成员 class Super{ void superMethod(){} } class Sub extends Super{ void subMethod(){} } class Sub2 extends Super{ void subMethod2(){} } static <T extends Super> void processSuper(T input){ // t

当有可能输入子类作为参数时,为什么具有上限的泛型通配符函数不允许访问子类的成员

class Super{
    void superMethod(){}
}
class Sub extends Super{
    void subMethod(){}
}
class Sub2 extends Super{
    void subMethod2(){}
}

static <T extends Super> void processSuper(T input){
    // this is safe and compiles
    input.superMethod();

    // this doesn't compile
    input.subMethod();

    // nor this
    input.subMethod2();
}
这可以编译,但被认为是非常糟糕的样式(紧密耦合)。 更好的OO设计是将
superMethod()
委托给
Sub
Sub2
的不同功能


TL;博士
因为编译器不知道子类型,所以无法实现您想要的。即使它真的起作用了,那也是糟糕的面向对象设计。

回答这样一个一般性的问题是不可能的。请分享一些代码,并强调您到底遇到了什么问题。阅读以下答案:欢迎使用堆栈溢出!欢迎来到Stack Overflow!寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参见:如何创建。使用“编辑”链接改进您的问题-不要通过评论添加更多信息。谢谢同样的原因,任何变量都不允许访问其类型的子类的成员。因为它可能是一个子类,或者是另一个子类,或者根本不是子类。你在说什么?
if(input instanceof Sub){
    ((Sub) input).subMethod();
}