首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java 多态性举例来说

2012-09-19 
java 多态性举例?自己比较懒,上次面试遇到这个问题,回来查了下。网上查了,大概有这两种例子。1.一种是普通的

java 多态性举例

?

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

?

1.网上摘抄:

?

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

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

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

?

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{ ?????public?static?void?main(String[]?args)?{ ?
  2. ????????Circle?circle?=?new?Circle(12.98); ?????????Sphere?sphere?=?new?Sphere(25.55); ?
  3. ? ?????????Shape?shape?=?circle;???????//向上转型 ?
  4. ????????//多态调用 ?????????shape.computeArea(); ?
  5. ????????shape.computeVolume(); ?????????System.out.println("circle?area:?"?+?shape.getArea()); ?
  6. ????????System.out.println("circle?volume:?"?+?shape.getVolume()); ?????????//多态调用 ?
  7. ????????shape?=?sphere; ?????????shape.computeArea(); ?
  8. ????????shape.computeVolume(); ?????????System.out.println("Sphere?area:?"?+?shape.getArea()); ?
  9. ????????System.out.println("Sphere?volume:?"?+?shape.getVolume()); ?????} ?
  10. }
 

热点排行