【问题标题】:Why cant we are able to create chield class object to its own type when constructor method of parent is used to create Object in Javajava - 为什么在Java中使用父类的构造函数方法创建对象时,我们不能将子类对象创建为自己的类型
【发布时间】:2021-02-07 03:00:10
【问题描述】:

第 1 步:父类

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

第 2 步:Child 类

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(); 
        
    }
}

//给我一个运行时错误 //线程“main”中的异常 java.lang.ClassCastException: class com.swapnil.Parent 不能 //cast to class com.swapnil.Chield (com.swapnil.Parent 和 com.swapnil.Chield 在未命名的//模块中加载程序“应用程序”)

【问题讨论】:

  • 您为什么希望这会起作用?为什么父母也是孩子?

标签: java


【解决方案1】:

这不会给你一个编译时错误,因为你正在类型转换并且编译器认为它是故意完成的并且是可能的。但它给出了运行时错误,因为这是不可能的。父类不能转换成子类。

【讨论】:

    猜你喜欢
    • 2014-07-16
    • 2011-09-07
    • 2010-10-12
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    相关资源
    最近更新 更多