无法将类强制转换为其子类?

Geo*_*ton 2 java casting

class Mid1Prob1 {
    public static void main(String[] args) {
        System.out.println("Testing...");
        int x = 3;
        System.out.println(3);
        System.out.println((int) x); // legal to cast primitive value to the same type as itself
        System.out.println((long) x); // legal to cast primitive value to a super type
        System.out.println((short) x); // legal to cast a primitive value to a sub type, but may lose information

        Actual act = new Actual();
        System.out.println(((Actual) act) .x); // legal to cast a reference value to the same class as itself
        System.out.println(((Super) act) .x); // legal to cast a reference value to a superclass of itself, as long as the superclass is actually a superclass of the current class
        System.out.println(((Sub) act) .x); // run-time error, cannot cast a reference value to its subclass
    }
}

class Super {
    public int x = 999;
}

class Actual extends Super {
    public int x = 666; // variables can be public in package-private class
}

class Sub extends Actual {
    public int x = 333;
}
Run Code Online (Sandbox Code Playgroud)

请检查main()方法的最后一行,并将其与上面段落的最后一行进行比较.当我可以将int转换为short时,为什么我不能将引用值转换为其子类?

Mar*_*oun 5

当你这样做

(Sub) act
Run Code Online (Sandbox Code Playgroud)

你告诉编译器(通过显式转换)相信你没有犯错,所以它忽略了错误,并且在编译时没有检测到它.但是当程序运行时,你会得到一个例外,因为actIS Actual,而不是一个Sub.