0

I am trying to understand why the following is not compiling.

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

        }
}

As I understand I can use anything that IS A Animal or super type of Animal(in this case Object). Can any one explain?

Compiler Message:

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 Answers1

2

The problem is you can't specify a lower bound for a generic parameter:

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

You can only specify an upper bound:

public class AnimalHolder<T extends Animal> { // Must use "extends"
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • To be honest, I didn't understand the difference between the two. That is why I posted this question. –  Apr 20 '14 at 12:07
  • `T super X` isn't very useful if you think about it. All you can say for sure is T is `Object`, which tells you nothing. Read the duplicate question for more info. – Bohemian Apr 20 '14 at 12:10