標籤:style blog color os ar div sp c log
利用繼承實現軟體複用
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 Animal19 { 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 Animal28 { 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 Bird20 {21 private Animal a; 22 public Bird(Animal a){23 this.a = a; //this.a = a = a1 = [email protected]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 Wolf34 {35 private Animal a;36 public Wolf(Animal a){37 this.a = a; //this.a = a = a2 = [email protected]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 CompositeTest48 {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 }
利用繼承和組合實現軟體複用