我沿着代码行提到的意见,我想了解即如下:ClassCastException异常铸造一个基类对象扩展基类的类时,
我didnt't理解这行代码:
Xyz obj3=(Xyz) obj1;
Abc
不能转换到Xyz
类型。编译,但是在执行过程中返回异常:Xyz obj2=(Xyz)new Abc();
class Abc { Abc() { System.out.println(" Hello "); } void show() { System.out.println("Conco constructor w/ Super Class"); } } class Xyz extends Abc { Xyz() { System.out.println(" Hi "); } void display() { System.out.println("ConsNew3 constructor w/ Extends Class Conco"); } public static void main(String arg[]) { Xyz obj=new Xyz(); Abc obj1=new Xyz(); obj1.show(); Xyz obj3=(Xyz) obj1; // I didnt't understand this line of code /*Xyz obj2=(Xyz)new Abc(); Abc cannot be cast to Xyz type . Compiled , but returns exception during execution */ } }
2 /狗是动物,但动物并不总是狗 –
这似乎并不约为隐性或显性的构造函数。它关于[多态性](https://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29)。 – khelwood
@RC。逻辑的解释,可以帮助超过变形的方法。希望,你不介意通知它? – 1ambharath