Java泛型超级用法

时间:2014-04-20 11:44:48

标签: java generics

我试图理解为什么以下不编译。

public class AnimalHolder<T super Animal> {
        T animal;
        public static void main(String[] args) {
                AnimalHolder<Object> objectHolder = new AnimalHolder<Object>();

        }
}

根据我的理解,我可以使用IS A Animal或超级Animal(在这种情况下为Object)的任何内容。任何人都可以解释一下吗?

  

编译器消息:

AnimalHolder.java:15: error: > expected
public class AnimalHolder<T super Animal> {
                           ^
AnimalHolder.java:15: error: <identifier> expected
public class AnimalHolder<T super Animal> {
                                        ^
AnimalHolder.java:17: error: illegal start of expression
        public static void main(String[] args) {
        ^
AnimalHolder.java:17: error: illegal start of expression
        public static void main(String[] args) {
               ^
AnimalHolder.java:17: error: ';' expected
        public static void main(String[] args) {
                     ^
AnimalHolder.java:17: error: '.class' expected
        public static void main(String[] args) {
                                         ^
AnimalHolder.java:17: error: ';' expected
        public static void main(String[] args) {
                                             ^
AnimalHolder.java:21: error: reached end of file while parsing
}
 ^
8 errors

1 个答案:

答案 0 :(得分:2)

问题是您无法为通用参数指定 lower 界限:

public class AnimalHolder<T super Animal> { // Can't do this

您只能指定上限绑定:

public class AnimalHolder<T extends Animal> { // Must use "extends"