A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 庄星睿 中级黑马   /  2012-6-11 17:28  /  1437 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

先用继承实现以下 Animal  ,Bird ,Wolf之间的关系
  1. class Animal
  2. {
  3. private void beat()
  4. {
  5. System.out.println("心脏跳动.........");
  6. }
  7. public void breath()
  8. {
  9. beat();
  10. System.out.println("呼吸.......");
  11. }

  12. }

  13. class Bird extends Animal
  14. {
  15. public void fly()
  16. {
  17. System.out.println("flying.......");
  18. }

  19. }

  20. class Wolf extends Animal
  21. {
  22. public void run()
  23. {
  24. System.out.println("running.......");

  25. }

  26. }

  27. public class InheritTest
  28. {
  29. public static void main(String[] args)
  30. {
  31. Bird b=new Bird();
  32. b.breath();
  33. b.fly();

  34. Wolf w=new Wolf();
  35. w.breath();
  36. w.run();

  37. }

  38. }
复制代码
先不考虑别的,如果用组合的方式实现代码复用:
  1. class Animal
  2. {
  3. private void beat()
  4. {
  5. System.out.println("心脏跳动........");
  6. }
  7. public void breath()
  8. {
  9. beat();
  10. System.out.println("呼吸........");
  11. }
  12. }


  13. class Bird   
  14. {
  15. private Animal a;
  16. public Bird(Animal a)
  17. {
  18. this.a=a;
  19. }
  20. public void breath()
  21. {
  22. a.breath();
  23. }
  24. public void fly()
  25. {
  26. System.out.println("flying.......");
  27. }
  28. }

  29. class Wolf
  30. {
  31. private Animal a;
  32. public Wolf(Animal a)
  33. {
  34. this.a=a;
  35. }
  36. public void breath()
  37. {
  38. a.breath();
  39. }

  40. public void run()
  41. {
  42. System.out.println("running.......");

  43. }

  44. }

  45. public class CompositeTest
  46. {
  47. public static void main(String[] args)
  48. {
  49. Animal a1=new Animal();
  50. Bird b=new Bird(a1);
  51. b.breath();
  52. b.fly();

  53. Animal a2=new Animal();
  54. Wolf w=new Wolf(a2);
  55. w.breath();
  56. w.run();


  57. }

  58. }
复制代码
代码比较简单,但能表达组合就是将原来父类Animal嵌入进子类中,从而成为了子类中的一部分,就是"has a"关系,在内存空间上,组合比继承多一个在栈内存中的引用那个父类对象的引用变量,当然这里还是用继承好一些,那个关于聚合的例子谁给一个,最好能简单说明问题滴,视频里只是说了一下聚合和组合的紧密程度不同,那聚合的实现方式也应该和组合一样吧,谁给一个详细实现方式的例子

评分

参与人数 1技术分 +1 收起 理由
黄奕豪 + 1 赞一个!

查看全部评分

1 个回复

正序浏览
C++中的组合好像用的比较多
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马