gpt4 book ai didi

java - 关于重载方法的泛型查询

转载 作者:行者123 更新时间:2023-11-29 04:58:47 25 4
gpt4 key购买 nike

我正在阅读来自 JavaDocs 的这个例子在第一个示例中,文档说它将调用 setData(Object) 方法,但是当我尝试代码时它从不调用该方法,而是调用 setData(Integer data)方法。

但是当我实现这个例子时它给出了运行时异常

java.lang.ClassCastException at n.setData("Hello");

public class Node<T> {
public T data;

public Node(T data) {
this.data = data;
}

public void setData(T data) {
System.out.println("Node.setData");
this.data = data;
}
}

public class MyNode extends Node<Integer> {
public MyNode(Integer data) {
super(data);
}

public void setData(Integer data) {
System.out.println("MyNode.setData");
super.setData(data);
}
}

但是文档说:

MyNode mn = new MyNode(5);
Node n = mn; // A raw type - compiler throws an unchecked warning
n.setData("Hello");
Integer x = mn.data; // Causes a ClassCastException to be thrown.

ClassCast 异常将出现在第 4 行。它不会那样发生。

最佳答案

发生的事情已经在同一教程中进行了解释。

  • n.setData("Hello"); causes the method setData(Object) to be executed on the object of class MyNode. (The MyNode class inherited setData(Object) from Node.)
  • In the body of setData(Object), the data field of the object referenced by n is assigned to a String.
  • The data field of that same object, referenced via mn, can be accessed and is expected to be an integer (since mn is a MyNode which is a Node<Integer>.
  • Trying to assign a String to an Integer causes a ClassCastException from a cast inserted at the assignment by a Java compiler.

所以,如您所见,这就是您所经历的。尝试将字符串分配给整数时,方法调用会导致异常。

令人困惑的是代码中的注释可能放错了地方。它试图告诉您代码不会到达第 4 行,因为到那一点将抛出异常。但是,如果注释在实际抛出异常的第 3 行,会更清楚。

关于java - 关于重载方法的泛型查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32795307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com