1

I don't understand why the following code does compile.

public  class House<T> {
    static <T> void live(House<T> a) {}

    static {
        new House<Integer>() {
            {
                this.live(new House<String>());
            }
        };
    }

}

type T in static code in new House is an Integer, so the required type of argument to live function is House<Integer>, whereas it compiles with House<String>.

Please explain.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
hungry91
  • 133
  • 8
  • 1
    Why do you think, you have to declare a generic type for the method if you want to use the generic type of the class instance (`T` of `House`)? And why is that method static? – Tom May 14 '15 at 10:24

1 Answers1

7

You declared generic type T two times:

  • in public class House<T>
  • and in static <T> void live(House<T> a)

which means that they are two different generic types (they have nothing to do witch each other, even if they have same name).

In other words your code is same as

public class House<T> {

    static <E> void live(House<E> a) {}

    static {
        new House<Integer>() {
            {
                this.live(new House<String>());
            }
        };
    }

}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • So what is the way to enforce that those T's in class definition and function represent the same type? – hungry91 May 14 '15 at 10:19
  • Oh now i see, just remove from function? – hungry91 May 14 '15 at 10:20
  • 2
    You can't do it since your method is static, which means it belongs to class while `T` is non-static and can change in each instance. In other words you can't limit generic type of method which doesn't belong to instance with generic type of instance. What if you wouldn't have an instance? Or what if there would be more than one instances with different generic types? Which should be generic type of `live` method? – Pshemo May 14 '15 at 10:24
  • @hungry91 You can read more about this subject in this question [Static method in a generic class?](http://stackoverflow.com/questions/936377/static-method-in-a-generic-class). – Pshemo May 14 '15 at 10:32
  • @Pshemo Accessing anything `static` with a reference is a bad idea as anything `static` should be accessed with the `class` name. (Even if the reference is `this`) – Chetan Kinger May 14 '15 at 10:48
  • 1
    @ChetanKinger True, but that is different problem which I didn't want to focus on in my answer. I just wanted to show that both generic types declared by OP are independent. – Pshemo May 14 '15 at 10:50