Java将子项转换为父项

alp*_*a09 4 java

Lion类扩展了Animal.

这是我的代码:

Animal a = new Animal();
Lion b = new Lion();
Animal c = (Animal) b;

Animal[] arr = { a, b, c };

for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i].getClass().getName());
    arr[i].run();
}
Run Code Online (Sandbox Code Playgroud)

结果是:

test2.Animal

动物运行......

test2.Lion

狮子跑......

test2.Lion

狮子跑......

从例子看,"c"似乎是"狮子",而不是"动物".为什么会这样?

T.J*_*der 10

从例子看,"c"似乎是"狮子",而不是"动物".为什么会这样?

因为c 狮子:

Lion b = new Lion();   // Creates a Lion
Animal c = (Animal) b; // Refers to the Lion through an Animal variable
Run Code Online (Sandbox Code Playgroud)

现在,cAnimal一个Lion对象的类型引用.对象仍然是Lion,它只是对它的引用仅限于Animal东西.因此,当你向对象询问它的​​类是什么时(不是你的接口c你的数组中的变量/第三个条目),它告诉你它是一个Lion.

这正是这种情况:

Map m = new HashMap();
Run Code Online (Sandbox Code Playgroud)

m参考类型Map,所以你只能用它访问的东西Map接口定义,但对象它指的是一个HashMap实例.


Men*_*ena 2

您正在调用getClass.

方法调用在运行时解析,因此它打印Lion而不是Animal.