java - ClassCastException 冒险

标签 java classcastexception

我有 -

class A {
    // contains certain set() and get() methods
}

class B extends A {
    public A getAotherMethod() {
      A a = new A();
      // Contains some logic
      return a
      }
}

class C extends B {
    // contains certain set() and get() methods
}

class D {
    public Object getMethod() {

      B b = new B();
      // Contains some logic
      return b.getAnotherMethod()
     }
}


public static void main(String[] args) {
    A a = new A();
    B b = new B();
    C c = new C();
    D d = new D();
    c = (C) d.getMethod(); // This is giving me ClassCastException
}

最佳答案

d.getMethod();

这将在内部调用b.getAnotherMethod(),其中有

A a = new A();
// Contains some logic
return a

A 类的对象无法转换为C 类

我们可以将子类对象分配给父类(super class)引用,但我们不能将父类(super class)对象分配给子类引用,什么是在这种情况下由您完成。

关于java - ClassCastException 冒险,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10006106/

相关文章:

java - SerializationProxy 模式给出 ClassCastException : How to avoid?

java - 奇怪的类强制转换异常

android - ClassCastException:android.inputmethodservice.KeyboardView 无法转换为 com.support.mukhtar.simplekeyboard.CustomKeyboardView android

java - 将对象编码为 xml 并删除 xmlns

java - GridView项目合并android

java - 将按钮放在 google map API 的右上角

java - 为什么 Hibernate 在调用 session.save(object) 时会抛出 ClassCastException?

java - 无法转换为 java.lang.Comparable

java - Hibernate hikaricp 数据源

java - 如何让 Swagger UI 的参数成为下拉菜单而不是文本输入