为什么此代码具有运行时错误与编译错误

时间:2017-02-15 08:40:23

标签: java templates generics compilation runtime

所以我在这里有这个代码:想知道为什么下面的两个例子给出了运行时错误和编译错误

public abstract class Person<Mate> {
  public String name;
  public abstract Person<?> mate(Mate m);

  public static class Male extends Person<Person<?>.Female> {
    public Person<?> mate(Person<?>.Female m) {
      return null;
    }
  }

  public class Female extends Person<Male> {
    public Person<?> mate(Male m) {
      return null;
    }
  }
}

任何人都可以告诉我为什么这个代码示例会产生运行时错误

Person p = new Male();
p.mate(p);

虽然这个给出了编译错误

Person p<Female> = new Male();
p.mate(p); // Argument is of incorrect type.

1 个答案:

答案 0 :(得分:1)

这是因为:

Person p = new Male();

是使用Raw Types

的示例

使用任何原始类型会导致JVM执行非常奇怪的操作。不要使用它们。

相关问题