YADKAR

 Java 代码正尝试将对象转换到一个错误的类型。

package com;
class A
{
    int i = 10;
}

class extends A
{
    int j = 20;
}

class extends B
{
    int k = 30;
}

public class ClassCastExceptionDemo
{
    public static void main(String[] args)
    {
        A a = new B();   //B type is auto up casted to A type
        B b = (B) a;     //A type is explicitly down casted to B type.
        C c = (C) b;    //Here, you will get class cast exception
        System.out.println(c.k);
    }
}
这会导致发生错误,因为父类不能直接一个子类,确保新的类型归属于正确的类或者它的父类。

分类:

技术点:

相关文章:

  • 2021-12-17
  • 2022-12-23
  • 2021-11-02
  • 2021-05-31
  • 2021-08-06
  • 2021-11-03
  • 2022-01-15
  • 2021-11-13
猜你喜欢
  • 2021-12-05
  • 2022-12-23
  • 2021-12-15
  • 2022-01-14
  • 2021-09-25
相关资源
相似解决方案