Generics compiling even if wrong

Viewed 37

I have written generics code many times, without too much trouble. However, I just wrote some code that go wrong at runtime, and it is fine. But it should, in my understanding, also issue a compiler error, but it does not. Can anyone explain why?


import static org.junit.Assert.assertNotNull;

import org.junit.Test;

public class TestGenerics {
    interface I{}
    class A implements I{}

    private <Z extends I> Z get(){
        return (Z) new A();
    }

    @Test
    public void test() {
        A a1 = get();
        assertNotNull(a1);
        String b = get(); // this compiles. Why?
    }

}

Edit: don't focus on the cast to Z. I want to understand why the signature of the method say that It Is going to return something that implements I and i can assign It to a String without casting, as if String Is instanceof I which Is not

0 Answers
Related