【发布时间】:2018-01-02 07:21:15
【问题描述】:
这是我写的一个简单的代码:
class c1
{
int x = 10;
}
class c2 extends c1
{
int x = 20;
}
class c3
{
public static void main(String [] args)
{
c1 a = new c2();
System.out.println(a.x); //This works and output is 10.
System.out.println((c2)a.x); //Error is here
}
}
错误显示,
incompatible type, int cannot be converted to c2
我确定代码是正确的。 由于引用 a 的类型转换为 c2(在显示错误的语句中),因此应该显示 20。
但是,没有发生类型转换。 为什么?
【问题讨论】:
-
您的代码毫无意义。您正在尝试将 x 从 a (这是一个 int)转换为 c2 类型。