利用继承实现软件复用
1 class Animal
2 {
3 private String type;
4 public Animal(String type){
5 this.type = type;
6 }
7 public void beat(){
8 System.out.println(this.getType()+"心脏在不停跳动。。。");
9 }
10 public void breath(){
11 beat();
12 System.out.println(this.getType()+"呼吸中。。。");
13 }
14 public String getType(){
15 return this.type;
16 }
17 }
18 class Bird extends Animal
19 {
20 public Bird(String type){
21 super(type);
22 }
23 public void fly(){
24 System.out.println(this.getType()+"在天空自由自在的飞翔");
25 }
26 }
27 class Wolf extends Animal
28 {
29 public Wolf(String type){
30 super(type);
31 }
32 public void run(){
33 System.out.println(this.getType()+"在天空自由自在的飞翔");
34 }
35 }
36 public class AnimalTest
37 {
38 public static void main(String[] args)
39 {
40 Bird b = new Bird("鸟");
41 b.breath();
42 Wolf c = new Wolf("狼");
43 c.breath();
44 }
45 }
利用组合实现软件复用
2 class Animal //该类里的方法或Filed应是复用对象共同拥有的
3 {
4 private String type;
5 public Animal(String type){
6 this.type = type;
7 }
8 public void beat(){
9 System.out.println(this.getType()+"心脏在不停跳动。。。");
10 }
11 public void breath(){
12 beat();
13 System.out.println(this.getType()+"呼吸中。。。");
14 }
15 public String getType(){
16 return this.type;
17 }
18 }
19 class Bird
20 {
21 private Animal a;
22 public Bird(Animal a){
23 this.a = a; //this.a = a = a1 = Animal@1db9742
24 }
26 public void breath(){
27 a.breath(); //a1.bteath();
28 }
29 public void fly(){
30 System.out.println((this.a).getType()+"在天空自由自在的飞翔");
31 }
32 }
33 class Wolf
34 {
35 private Animal a;
36 public Wolf(Animal a){
37 this.a = a; //this.a = a = a2 = Animal@106d69c
38 }
39 public void breath(){
40 a.breath();
41 }
42 public void run(){
43 System.out.println((this.a).getType()+"在陆地上自由奔跑");
44 }
46 }
47 public class CompositeTest
48 {
49 public static void main(String[] args)
50 {
51 Animal a1 = new Animal("鸟");
52 Bird b = new Bird(a1);
53 b.breath();
54 b.fly();
55 Animal a2 = new Animal("狼");
56 Wolf c = new Wolf(a2);
57 c.breath();
58 c.run();
59 }
60 }