1.继承关系这的向上转型
![](http://blog.51cto.com/attachment/200703/200703111173621555090.jpg)
Shape s=new Circle();
|
这里,创建了一个Circle对象,并把得到的引用立即赋值给Shape。通过继承,Circle就是一种Shape。
假设你调用基类方法(它已在导出类中被覆盖):
s.draw();
|
由于后期绑定(多态),将会正确调用Circle.draw()方法。
2.接口中的向上转型
如下面的例子所示:
interface CanFight {
void fight();
}
void fight();
}
interface CanSwim {
void swim();
}
void swim();
}
interface CanFly {
void fly();
}
void fly();
}
class ActionCharacter {
public void fight() {}
}
public void fight() {}
}
class Hero extends ActionCharacter
implements CanFight, CanSwim, CanFly {
public void swim() {}
public void fly() {}
}
implements CanFight, CanSwim, CanFly {
public void swim() {}
public void fly() {}
}
public class Adventure {
public static void t(CanFight x) { x.fight(); }
public static void u(CanSwim x) { x.swim(); }
public static void v(CanFly x) { x.fly(); }
public static void w(ActionCharacter x) { x.fight(); }
public static void main(String[] args) {
Hero h = new Hero();
t(h); // Treat it as a CanFight
u(h); // Treat it as a CanSwim
v(h); // Treat it as a CanFly
w(h); // Treat it as an ActionCharacter
}
}
public static void t(CanFight x) { x.fight(); }
public static void u(CanSwim x) { x.swim(); }
public static void v(CanFly x) { x.fly(); }
public static void w(ActionCharacter x) { x.fight(); }
public static void main(String[] args) {
Hero h = new Hero();
t(h); // Treat it as a CanFight
u(h); // Treat it as a CanSwim
v(h); // Treat it as a CanFly
w(h); // Treat it as an ActionCharacter
}
}
在Adventure类中,可以看到有四个方法把上面各种接口和具体类作为参数。当Hero对象被创建时,它可以被传递给这些方法中的任何一个,这意味着它依次被向上转型为每一个接口。
由于JAVA中这种设计接口的方式,使得这项工作并不需要程序员付出任何特别的努力。