gpt4 book ai didi

java - 原始类型将 super 传递给 sub

转载 作者:行者123 更新时间:2023-12-01 14:30:59 25 4
gpt4 key购买 nike

根据此报价表http://www.onjava.com/pub/a/onjava/excerpt/javagenerics_chap05/index.html?page=2

Every parameterized type is a subtype of the corresponding raw type, so a value of the parameterized type can be passed where a raw type is expected. Usually, it is an error to pass a value of a supertype where a value of its subtype is expected, but Java does permit a value of a raw type to be passed where a parameterized type is expected—however, it flags this circumstance by generating an unchecked conversion warning. For instance, you can assign a value of type Stack<E> to a variable of type Stack, since the former is a subtype of the latter. You can also assign a value of type Stack to a variable of type Stack<E>, but this will generate an unchecked conversion warning.

此代码必须正确

public class Trial 
{
static void t(Stack<Integer> a )
{

}

public static void main( String[] args )
{
t( new s());
}
}

class s{

}
class Stack< T > extends s {
}

这是一个错误 t( new s());我问的是为什么给我错误,而不是如何解决问题!

最佳答案

Usually, it is an error to pass a value of a supertype where a value of its subtype is expected, but Java does permit a value of a raw type to be passed where a parameterized type is expected

...

I'm asking why give me error , not how to solve the problem

您收到错误是因为异常不适用 - 异常仅适用于在需要参数化类型的地方传递原始类型值。 s不是 Stack<T> 的原始类型; StackStack<T> 的原始类型.

您可以传递 Stack<T> 类型的值或者您可以传递原始类型 Stack 的值带有警告,但不能传递 s 类型的值因为在需要子类型的地方传递父类(super class)型的值是错误的,并且 s不是预期类型的​​原始类型 Stack<T> .

关于java - 原始类型将 super 传递给 sub,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16860032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com