Note that there are some explanatory texts on larger screens.

plurals
  1. POOverriding Java generic methods
    text
    copied!<p>I wanted to create an interface for copying an object to a destination object of the same class. The simple way is to use casting:</p> <pre><code>import org.junit.Test; import org.junit.internal.runners.JUnit4ClassRunner; import org.junit.runner.RunWith; @RunWith(JUnit4ClassRunner.class) public class TestGenerics { public static interface Copyable { public void copy(Copyable c); } public static class A implements Copyable { private String aField = "--A--"; protected void innerCopy(Copyable c) { A a = (A)c; System.out.println(a.aField); } public void copy(Copyable c) { innerCopy(c); } } public static class B extends A { private String bField = "--B--"; protected void innerCopy(Copyable c) { B b = (B)c; super.innerCopy(b); System.out.println(b.bField); } } @Test public void testCopy() { Copyable b1 = new B(); Copyable b2 = new B(); b1.copy(b2); } } </code></pre> <p>But also i've found a way it can be done using generics:</p> <pre><code>import org.junit.Test; import org.junit.internal.runners.JUnit4ClassRunner; import org.junit.runner.RunWith; @RunWith(JUnit4ClassRunner.class) public class TestGenerics { public static interface Copyable&lt;T&gt; { public void copy(T t); } public static class A&lt;T extends A&lt;?&gt;&gt; implements Copyable&lt;T&gt; { private String a = "--A--"; public void copy(T t) { System.out.println(t.a); } } public static class B&lt;T extends B&lt;?&gt;&gt; extends A&lt;T&gt; { private String b = "--B--"; public void copy(T t) { super.copy(t); System.out.println(t.b); } } @Test @SuppressWarnings("unchecked") public void testCopy() { Copyable b1 = new B(); Copyable b2 = new B(); b1.copy(b2); } } </code></pre> <p>Though the only way i've found to get rid of warnings is the annotation. And it feels like something is wrong. So what's wrong? I can accept that something is wrong in the root of the problem. So any sort of clarification is welcome.</p>
 

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