That was a beginner's question. All experienced Java'ers know how to use generic types. But what happens in some inappropriate using is the question we are discussing here.
Consider the code below:
We all know that subclass Test must have a type bounding for Super. For example, extends Super<String>. But here is no such bounding, so it may have errors or warnings at compile time. And what are the implicated problems? I experimented with this code and had the following conclusion:import java.lang.reflect.*; class Super<T> { public void method (T t) { System.out.println("Hello"); } public void method2 () { } } public class Test extends Super { /*public void method (Object t) { System.out.println("world"); }*/ /*public <T> void method (T t) { }*/ public static void main (String args[]) { new Test().method(""); for (Method m : Test.class.getMethods()) { System.out.println(m.toGenericString()); } } }
If I comment bothmethod()in the subclass, it is compiled with a warning:Test.java uses unchecked or unsafe opertations. In the running result, it turned the generic typeTintoObject:public void Test.method(java.lang.Object). If I only uncomment the firstmethod()in the subclass, it is compiled with no warnings. In the running result, the subclass owns
onepublic void Test.method(java.lang.Object). But it doesn't allow@Overrideannotation or it throws an error: method does not override . If I only uncomment the secondmethod()in the subclass (which also has a generic type bounding), the compile fails with an error:name clash. It also doesn't allow@Overrideannotation. If you do so, it throws a different error:method does not override.method2()is inherited by the subclass unanimously. But you also can't write the following code:in superclass:public void method2 (Object obj)and in subclass:public <T> void method2 (T obj). They are also ambiguous and is not allowed by the compiler,name clashagain.
No comments:
Post a Comment