1

What's the proper way of setting temp2.in in the below snippet? Why does the code not compile?

public class WildCards {
    public static void main(String[] args) {
        TheBox<Integer> temp1 = new TheBox<Integer>();
        temp1.set(10);
        TheBox<? extends Number> temp2 = temp1;
        temp2.set(1);
    }

    public static class TheBox<T> {
        T in;

        public T get() {
            return in;
        }

        public void set(T in) {
            this.in = in;
        }
    }    
}
declension
  • 3,764
  • 19
  • 23
hungry91
  • 121
  • 7
  • `TheBox extends Number>` could be e.g. `TheBox`. We can't be sure whether it is `TheBox` and can accept `int` values or not. – Bubletan Apr 26 '15 at 11:47
  • Excellent answer to a very similar question: http://stackoverflow.com/a/4343547/683077 – Colin M Apr 26 '15 at 11:54

1 Answers1

1

Because you are only allowed to do with temp2 things that are legal to do with TheBox parametrized by any possible subclass of Number. That includes subclasses of Number that haven't even been written yet. Integer can only be assigned to some subclasses of Number but not all.

The only legal argument to give to temp2.set is null. That's because null can be assigned to anything.

Please clarify what you mean by "whats the proper way of setting temp2.in". Proper in what way? What is the desired behavior of this code?

Misha
  • 25,007
  • 4
  • 52
  • 71
  • Thanks for the answer. I thought the methods I am allowed to use are Object's methods not the reference's. I would also like to know if there is a way to somehow set temp2.in to Interger.valueOf(1). – hungry91 Apr 26 '15 at 12:54