- 多态体现在两方面
- 方法的重载和覆写(方法的多态)
- 对象的多态(接口来实现)
- 两种情况
- 向上转型:父类 父类对象=子类实例(利用接口实现,常用)
- 向下转型:子类 子类对象=(子类)父类示例,(利用继承实现,基本不用)
- 扩展时,上层代码不用改,下层随便改,这种现象就叫多态,可以分工同时工作,提高效率
- public interface IPlane {
- public void canFly();
- }
- public interface IShip {
- public void canFloat();
- }
- public class ShipPlane implements IShip,IPlane{
- @Override
- public void canFloat() {
- System.out.println("水上飞机会漂");
- }
- @Override
- public void canFly() {
- System.out.println("水上飞机会飞");
- }
-
- }
- public class Test {
- public void byShip(IShip iship){
- iship.canFloat();
- }
- public void byPalne(IPlane iplane){
- iplane.canFly();
- }
- public static void main(String[] args) {
- Test t=new Test();
- IPlane ip=new ShipPlane();
- t.byPalne(ip);
- }
- }
- public class XiaoYingHao implements IShip{
- @Override
- public void canFloat() {
- System.out.println("小鹰号航母在漂浮");
- }
- }
- public class ZhiShengFeiJi implements IPlane{
- @Override
- public void canFly() {
- System.out.println("直升飞机在飞");
- }
-
- }
复制代码 |