gpt4 book ai didi

java - 继承中的 ClassCastException - 为什么?

转载 作者:行者123 更新时间:2023-12-01 00:09:45 25 4
gpt4 key购买 nike

以下代码抛出 ClassCastException :

Exception in thread "main" java.lang.ClassCastException: class Child cannot be cast to class java.util.List (Child is in unnamed module of loader 'app'; java.util.List is in module java.base of loader 'bootstrap') at Test.main(Test.java:20)

我真的不确定为什么会这样。我认为我编写了正确的代码。

public class Test {
public void a(ParentI... ss) {
}

public void a(List<ParentI> ss) {
}


public <R extends ParentI> R makeParent() {
ParentI ai = new Child();
return (R) ai;
}

public static void main(String[] args) {
Test al = new Test();
al.a(al.makeParent());
}
}


interface ParentI {
public void a();
}

class Parent implements ParentI {
public void a() {
System.out.println("Parent");
}
}

class Child extends Parent {
public void a(int t) {
System.out.println("child");
}
}

请帮助我理解这个问题以及如何解决这个问题。

最佳答案

编译器推断 al.makeParent() 返回的类型根据a()方法被方法重载决议选择。

由于方法重载决议首先考虑没有 vararg 参数的候选者,所以只有 public void a(List<ParentI> ss)考虑了过载,因此这是选择的过载。

原因public void a(List<ParentI> ss)可以接受返回 R extends ParentI 的方法的返回值作为其参数是可能存在一个扩展 ParentI 的类并实现 List<ParentI> .

一旦public void a(List<ParentI> ss)选择过载,在 return (R) ai; 中进行类型转换导致尝试转换 Child实例到 List ,在运行时失败。

例如,如果您更改了 Child 的定义类:

class Child extends Parent implements List<ParentI>

您的代码将无一异常(exception)地运行。

关于java - 继承中的 ClassCastException - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59658611/

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