Total Pageviews

24 Jan 2013

Some facts about generic types in Java

I answered a post on StackOverflow: http://stackoverflow.com/questions/14391027/java-generics-in-android/14392088#14392088

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:
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());
        }
    }
}
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:
  • If I comment both method() in the subclass, it is compiled with a warning: Test.java uses unchecked or unsafe opertations. In the running result, it turned the generic type T intoObjectpublic void Test.method(java.lang.Object).
  • If I only uncomment the first method() in the subclass, it is compiled with no warnings. In the running result, the subclass owns
    one public 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 second method() 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.

A Strange Bug in Python

Try out the following code, including the comments:

''''\xf1''''