3

我有一些代码如下:

public class java_generic {

    public static void main(String[] args) {

        T t = new X();
        t.<Object>m(new Object());
        t.<String>m(new String());

    }

    static class T {
        <E> void m (E e){
            System.out.println("here is T");
        }
    }

    static class X extends T {
        void m (String o){
            System.out.println("here is X");            
        }
    }

}

据我了解,类型擦除后,类T将变为:

    static class T {
        void m (Object e){
            System.out.println("here is T");
        }
    }

并且 m 过载。

拥有m(Object)and m(String),我希望结果是

here is T
here is X

然而,结果是

here is T
here is T

我想知道为什么结果会是这样。

4

2 回答 2

7

你几乎回答了你自己的问题。你只需要完全遵循后果。擦除所有代码,你会得到:

public class java_generic {

    public static void main(String[] args) {
        T t = new X();
        t.m(new Object());
        t.m(new String());
    }

    static class T {
        void m (Object e){
            System.out.println("here is T");
        }
    }

    static class X extends T {
        void m (String o){
            System.out.println("here is X");            
        }
    }
}

希望这很明显X.m不会覆盖T.m,因此通过T引用的调用永远不会调用X.m

于 2015-12-08T17:36:27.793 回答
2

由于T是 X 的超类,并且X的实例被分配给超类 Object t,因此您无法真正访问子类X方法。因此两者

   t.<Object>m(new Object());
   t.<String>m(new String());

调用超类泛型方法。

现在检查这种方式 -

public class java_generic {

    public static void main(String[] args) {
        X x = new X();
        x.<Object>m(new Object());
        x.<String>m(new String());

    }

    static class T {
        <E> void m (E e){
            System.out.println("here is T");
        }
    }

    static class X extends T {
        void m (String o){
            System.out.println("here is X");            
        }
    }

}
于 2015-12-08T17:58:15.310 回答