2

Why fist call of f() compiles fine? The argument given (and Boxed) is Integer, but explicit type witness is String! It should fail at compile time - just like it fails in the second call.

 class Test<T> {
        <S> void f(S arg) {
        }
    }

   // for My<T> both f() calls give same resuls...
    public class My {

        public static void main(String[] args) {

            Test obj = new Test<>();
            obj.<String>f(4); // compiles (and runs) fine!

            //c.ERR
            //parameterized method <String>f(String) of type Test<Object> 
            //is not applicable for the arguments (Integer)
            new Test<>().<String>f(4);

But if I make Test not a generic class, compilation fails as expected:

class Test {
    <S> void f(S arg) {
    }
}

public class My {
    public static void main(String[] args) {        

        Test obj = new Test();      
        // compile err
        //parameterized method <String>f(String) 
        //of type Test is not applicable for the arguments (Integer)
        obj.<String>f(4);
    }   
}

P.S. Eclipse compiler, SE7 mode

Code Complete
  • 3,146
  • 1
  • 15
  • 38
  • 8
    because `obj` has a raw type. – Eran Oct 03 '17 at 11:07
  • See: [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Jesper Oct 03 '17 at 14:12

0 Answers0