在Java中,当使用父类的构造函数方法创建object时,为什么不能创建自己类型的chield类对象呢



步骤1:父类

public class Parent {
public void m1() {
System.out.println("parent m2");
}
}

步骤2:主要类

public class Chield  extends Parent{
public void m1() {
System.out.println("chield m1");
}
public void m2() {
System.out.println("chield m2");
}
}

步骤3:-

class Test{
public static void main(String []args) {

Chield c = (Chield) new Parent(); 

}
}

//给我一个运行时错误//线程中的异常";主";java.lang.ClassCastException:类com.swapnil.Pparent不能//强制转换为类com.swapnil.Chield(com.swapnil.Pparent和com.swapnil.Chield位于加载程序"app"的未命名//模块中(

这不会给您带来编译时错误,因为您正在进行类型转换,编译器认为这是故意的,而且是可能的。但它给出了运行时错误,因为这是不可能的。父类不能强制转换为子类。

最新更新