public Class Fruits{}
public Class Apple extends Fruits{}
public Class RedApple extends Fruits{}
Apple apple = new Apple();
//向上转-OK
Fruits fruits = (Fruits)apple;
//向下转-Wrong,因为苹果不一定就是红苹果.
RedApple redApple = (RedApple)apple;
//-------------------------------分割线---------------
RedApple redApple1 = new RedApple();
//向上转-OK, 苹果是水果
Fruits fruits = (Fruits)redApple1;
//向下转-OK, 由于上面的水果之前是红苹果, 那么将水果强转为红苹果也就没有问题了.
RedApple redApple2 = (RedApple)fruits;
本文详细介绍了Java中对象的向上转型和向下转型的概念及其使用场景。通过具体的代码示例,展示了不同情况下转型的正确性和可能存在的问题。特别是对于继承体系中的实例转型进行了深入探讨。

被折叠的 条评论
为什么被折叠?



