1

Sorry, maybe it is a silly question, but I can't find answer.

Two generics parameters on a method, could one extends another?

public class A {
}

public class B extends A {
}

public class C {
}

public class Foo {

    public static <R extends A> void f1 (A t, R r){
    }

    // T and R are generics parameter, R bounds on T
    public static <T, R extends T > void f2(T t, R r) {
    }

    public static void main(String[] args) {

        A a = new A();
        B b = new B();
        C c = new C();

        Foo.f1(a, b); // no error
        Foo.f1(a, c); // compile error, it's ok

        Foo.f2(a, b); // no error
        Foo.f2(a, c); // no error !  why? 
   }
}

The last f2 method call has no compile error, but I think C is not subclass of A, compile error should be arised. Any help?

1
  • Why do you think T is A? Commented Oct 11, 2016 at 18:55

1 Answer 1

3

Because type parameters in your code where you call the method are implicit and for example if java compiler infers T and R to Object it's fine, isn't it? But if you declare them explicit it raises an error:

 Foo.<A, C>f2(a, c); //error as you wished
 Foo.<Object, Object>f2(a, c); //no errors and it's ok, isn't it?
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.