Java:转换 ParentClass 和 ChildClass(向下转型运行时错误)

标签 java casting type-conversion downcast

public class InheritanceDemo {

    public static void main(String[] args) {

        ParentClass p = new ParentClass();
        ChildClass c = new ChildClass();

        //Casting ChildClass to ParentClass
        ParentClass pc = new ChildClass();
        pc.parentClassMethod(); //Output: Parent Class Method (as expected)

        //Again Casting Parent Class to ChildClass explictly
        //Question 1 for this code
        ChildClass cp = (ChildClass) pc;
        cp.parentClassMethod(); //Output: Parent Class Method (unexpected)

        ChildClass cc1 = (ChildClass) new ParentClass();
        cc1.parentClassMethod(); //Compiles, but Run Time Error

        ChildClass cc2 = (ChildClass) p;
        cc2.parentClassMethod(); //Compiles, but Run Time Error

    }
}

class ParentClass {

    public void parentClassMethod(){
        System.out.println("Parent Class Method");
    }

}

class ChildClass extends ParentClass {

    public void ParentClassMethod(){
        System.out.println("Parent Class Method From Child Class");
    }

    public void ChildClassMethod(){
        System.out.println("Child Class Method");
    }

}

问题1:

现在,我在 ParentClassChildClass 类中都有一个名为 parentClassMethod 的方法(重写)。当我将 ParentClass 转换为 ChildClass 然后调用 ParentClassMethod 时,如果 cp 引用 ChildClass,为什么它执行 ParentClass 方法而不是 ChildClass 中的方法?

问题2:

(i)ChildClass cp = (ChildClass) pc;

(ii)ChildClass cc1 = (ChildClass) new ParentClass(); (iii) ChildClass cc2 = (ChildClass) p;

如果 (i) 工作正常,为什么 (ii) 或 (iii) 不行?

因为我在这两种情况下都从 ParentClass 转换为 ChildClass

最佳答案

Now, I have a method called parentClassMethod in both ParentClass and ChildClass classes(Overridden).

不,你不知道。您在 ParentClass 中有一个名为 parentClassMethod 的方法,在 ChildClass 中有一个名为 ParentClassMethod 的方法。由于所有 Java 标识符都区分大小写,因此两者之间没有关联。 ParentClassMethod 不会覆盖 ParentClass 中的 parentClassMethod

If (i) is working fine, why not (ii) or (iii)?

在 (ii) 和 (iii) 中,您尝试将 ParentClass 实例转换为 ChildClass 实例。这是不允许的,因为 ChildClass 不是 ParentClass,就像 Object 不是 String 一样。

在 (i) 中,您尝试将 ChildClass 的实例(存储在声明为 ParentClass 的引用中)转换为 ChildClass,这是允许的。

进行转换时,重要的是运行时类型(换句话说,Tnew T() 中使用的类型)。

关于Java:转换 ParentClass 和 ChildClass(向下转型运行时错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14412093/

相关文章:

java - 是否有生成 DSL 解析器的工具不需要生成的解析器运行时?

sql - Postgres 在转换时在函数错误/失败时返回空值

c++ - 为什么这个涉及重载运算符和隐式转换的 C++ 表达式不明确?

java - Android Studio AsyncTask 返回对象困难

java - Windows Server 2003 上的奇怪 Java Swing UI NullPointerException

java - Spring Data REST "findBy..."未排序

C++模板函数将字符串拆分为数组

Java - 如何创建 Class<Map<Object,List<Object>>> 对象

arrays - ByteArray在Kotlin中 float

typescript - 从有区别的联合数组中查找的窄返回类型