继承VS组合
仅仅从代码复用的角度来看的化,组合完全可以替换继承
组合实例:
package com.bjsxt.oop.inherent;
/*
* 组合测试
*
*/
public class Animal2 {
public static void main(String args[]){
Bird2 Bird21=new Bird2();
Bird21.run();
Bird21.animal.eat();
}
String eye;
public void run() {
System.out.println("跑");
}
void eat() {
System.out.println("吃");
}
}
class Bird2 {
String eye;
Animal2 animal=new Animal2();//将Animal2当成一个属性
public void run() {
animal.run();
System.out.println("小鸟飞");
}
// public void eat() {
// System.out.println("吃");
// }
public void eggSheng() {
System.out.println("卵生");
}
}
组合比继承更灵活,他们都可以实现复用。

posted on 2016-03-11 14:00 1130136248 阅读(65) 评论(0) 收藏 举报
浙公网安备 33010602011771号