1 //Java中的继承和组合之间的联系和区别
2 //本例是继承
3
4 class Animal
5 {
6 private void beat()
7 {
8 System.out.println("心胀跳动...");
9 }
10 public void breath()
11 {
12 beat();
13 System.out.println("吸一口气,吐一口气,呼吸中...");
14 }
15 }
16 //继承Animal,直接复用父类的breath()方法
17 class Bird extends Animal
18 {
19 public void fly()
20 {
21 System.out.println("我在天空自由飞翔...");
22 }
23 }
24 //继承Animal,直接复用父类breath()方法
25 class Wolf extends Animal
26 {
27 public void run()
28 {
29 System.out.println("我在陆地上快速奔跑...");
30 }
31 }
32 public class InheritTest
33 {
34 public static void main(String[] args)
35 {
36 Bird b = new Bird();
37 b.breath();
38 b.fly();
39 Wolf w = new Wolf();
40 w.breath();
41 w.run();
42 }
43 }
1 //Java中的继承和组合之间的联系和区别
2 //本例是组合
3 class Animal
4 {
5 private void beat()
6 {
7 System.out.println("心胀跳动...");
8 }
9 public void breath()
10 {
11 beat();
12 System.out.println("吸一口气,吐一口气,呼吸中...");
13 }
14 }
15 class Bird
16 {
17 //将原来的父类组合到子类中来,作为子类的一个组合部分.
18 private Animal a;
19 public Bird(Animal a)
20 {
21 this.a = a;
22 }
23 //重新定义一个自己的breath()方法
24 public void breath()
25 {
26 //直接复用Animal提供的breath()方法来实现Bird的breath()方法
27 a.breath();
28 }
29 public void fly()
30 {
31 System.out.println("我在天空自在的飞翔...");
32 }
33 }
34 class Wolf
35 {
36 //将原来的父类组合到子类中来,作为子类的一个组合部分.
37 private Animal a;
38 public Wolf(Animal a)
39 {
40 this.a = a;
41 }
42 //重新定义一个自己的breath()方法
43 public void breath()
44 {
45 //直接复用Animal提供的breath()方法来实现Bird的breath()方法
46 a.breath();
47 }
48 public void run()
49 {
50 System.out.println("我在陆地上快速奔跑...");
51 }
52 }
53
54 public class CompositeTest
55 {
56 public static void main(String[] args)
57 {
58 //此时需要显示创建被组合的对象
59 Animal a = new Animal();
60 Bird b = new Bird(a);
61 b.breath();
62 b.fly();
63
64 //此时需要显示创建被组合的对象
65 Animal a2 = new Animal();
66 Wolf w = new Wolf(a2);
67 w.breath();
68 w.run();
69 }
70 }