Note that there are some explanatory texts on larger screens.

plurals
  1. POAdding a Generic allows you to override a method with a different return type?
    primarykey
    data
    text
    <p>I ran into this today and the only thing I can think is that this is a bug in the Java compiler. The following code compiles, but certainly seems incorrect (since testMethod has a differenet signature in the child but overrides the parent) and will throw class cast exceptions at runtime.</p> <pre><code>public interface TestInterface&lt;T&gt; { public List&lt;String&gt; testMethod(); // &lt;-- List&lt;String&gt; } public class TestClass implements TestInterface { @Override public List&lt;Integer&gt; testMethod() { // &lt;-- List&lt;Integer&gt; overriding List&lt;String&gt;!! return Collections.singletonList(1); } } </code></pre> <p>And using the above structure:</p> <pre><code>public void test() { TestInterface&lt;Boolean&gt; test = new TestClass(); List&lt;String&gt; strings = test.testMethod(); for (String s : strings) { System.out.println(s); } } </code></pre> <p>All of this compiles fine, but will obviously throw class cast exceptions if you run it. </p> <p>If you remove <code>&lt;T&gt;</code> from <code>TestInterface</code>, or fill <code>T</code> in in the line <code>TestClass implements TestInterface&lt;T&gt;</code> then the code will no longer compile, which makes sense. Imo <code>&lt;T&gt;</code> should have no bearing on the compilation of <code>testMethod</code> since it plays no part in that method. Maybe adding <code>&lt;T&gt;</code> to TestInterface is causing the compiler to type-erase the method signatures even though <code>T</code> doesn't participate in those methods...?</p> <p>Does anyone know what is going on here?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload