java 多态性举例

 

自己比较懒,上次面试遇到这个问题,回来查了下。网上查了,大概有这两种例子。
1.一种是普通的超类,子类覆盖父类的方法。
2.父类是抽象类,子类实现父类的抽象方法。

 

1.网上摘抄:

 

Game类是Football、Basketball、Popolong的父类,Games类使用前面4个类。

Java根据动态绑定决定执行“更具体”的方法,即子类方法。

  1. //Game.java
  2. package  cn.edu.uibe.oop;
  3. public   class  Game {
  4.   protected   void  play(){
  5.   System.out.println( "play game" );
  6.  }
  7. }
  8. //Football.java
  9. package  cn.edu.uibe.oop;
  10. public   class  Football  extends  Game {
  11.   protected   void  play() {
  12.     System.out.println( "play football" );
  13.      super .play();
  14.  }
  15.   void  f(){
  16.   play();
  17.  }
  18. }
  19. //Basketball.java
  20. package  cn.edu.uibe.oop;
  21. public   class  Basketball  extends  Game{
  22.   protected   void  play() {
  23.   System.out.println( "play basketball" );
  24.  }
  25. }
  26. //Popolong.java
  27. package  cn.edu.uibe.oop;
  28. public   class  Popolong  extends  Game {
  29.   protected   void  play() {
  30.   System.out.println( "play popolong" );
  31.  }
  32. }
  33. //Games.java
  34. package  cn.edu.uibe.oop;
  35. public   class  Games {
  36.   public   static   void  main(String[] args) {
  37.   Game[] games =  new  Game[ 10 ];
  38.   games[ 0 ] =  new  Basketball();
  39.   games[ 1 ] =  new  Football();
  40.   games[ 2 ] =  new  Popolong();
  41.   
  42.    for ( int  i= 0 ;i<games.length;i++){
  43.     if (games[i]!= null )
  44.       games[i].play();
  45.   }
  46.   
  47.  }
  48. }

 

2.from network

 

如在计算公司雇员工资的超类中

          // 用抽象方法作为多态接口 
    public abstract class Employee { 
        ... 
        public abstract double earnings();    //定义抽象方法作为多态接口 
    }
//这个方法将作为多态接口被子类的方法所覆盖 
    public class Manager extends Employee { 
    ... 
    public double eamings () return 0.0;

 

 

    抽象方法也可用protected.

  1. public   class  CircleShapeApp{  
  2.      public   static   void  main(String[] args) {  
  3.         Circle circle =  new  Circle( 12.98 );  
  4.         Sphere sphere =  new  Sphere( 25.55 );  
  5.    
  6.         Shape shape = circle;        //向上转型  
  7.          //多态调用  
  8.         shape.computeArea();  
  9.         shape.computeVolume();  
  10.         System.out.println( "circle area: "  + shape.getArea());  
  11.         System.out.println( "circle volume: "  + shape.getVolume());  
  12.          //多态调用  
  13.         shape = sphere;  
  14.         shape.computeArea();  
  15.         shape.computeVolume();  
  16.         System.out.println( "Sphere area: "  + shape.getArea());  
  17.         System.out.println( "Sphere volume: "  + shape.getVolume());  
  18.     }  
  19. }

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值