Overriding Java generic methods

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: 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); } } But also i've found a way it can be done using generics: 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(T t); } public static class A> implements Copyable { private String a = "--A--"; public void copy(T t) { System.out.println(t.a); } } public static class B> extends A { 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); } } 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.

以上就是Overriding Java generic methods的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏