【问题标题】:reason why this code has a runtime error vs compilation error此代码存在运行时错误与编译错误的原因
【发布时间】:2017-02-15 08:40:22
【问题描述】:

所以我在这里有这段代码:想知道为什么下面的 2 个示例会出现运行时错误和编译错误

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.

【问题讨论】:

  • 请将完成编译错误消息/运行时错误消息+堆栈跟踪添加到您的问题中。

标签: java templates generics compilation runtime


【解决方案1】:

这是因为:

Person p = new Male();

是一个使用Raw Types的例子。

使用任何原始类型都会导致 JVM 做一些非常奇怪的事情。不要使用它们。

【讨论】:

  • 同样使用原始类型会产生原始类型警告。注意警告。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多