之前我们说过继承可以通过组合来实现,这里我们来探讨两者的区别和用法。
1.概述
继承的主要作用:
- 代码的复用;
- 方便建模(is a)
组合的主要作用:
- 代码的复用;
- 方便建模(has a)
如果仅仅从复用的角度思考,组合完全可以代替继承。并且组合比继承更灵活。
2.代码分析
下面我们把如下继承代码通过组合实现:
继承代码:鸟类继承父类
public class Animal {
String name;
public Animal() {
super(); // 调用父类Object构造器
}
void eat() {
System.out.println("have a good dinner");
}
}
class Birds extends Animal {
public Birds() {
super();
}
@Override
void eat() {
super.eat(); // 调用父类的方法
System.out.println("-------------------"); // 分隔线
System.out.println("jiujiujiu");
}
void fly() {
System.out.println("Yeah,I can fly~~");
}
}
调用代码Test类
class Test {
public static void main(String[] args) {
Birds b = new Birds();
b.eat();
}
}
通过组合实现同样功能:
/**
* 测试组合
*
* @author Arvin
*
*/
public class Animal {
String name;
public Animal() {
super();
}
void eat() {
System.out.println("have a good dinner");
}
}
class Birds {
Animal animal = new Animal(); // 通过Animal对象完成组合
public Birds() {
super();
}
void eat() {
animal.eat(); // 调用Animal类的方法
System.out.println("-------------------"); // 分隔线
System.out.println("jiujiujiu");
}
void fly() {
System.out.println("Yeah,I can fly~~");
}
}
调用代码Test类:
public class Test {
public static void main(String[] args) {
Birds b = new Birds();
b.eat();
b.animal.eat(); // 也可以通过该方式调用Animal的eat方法
}
}
可见,通过组合同样可以实现继承的功能,而且,组合可以使用多个类的对象,类似于多继承,因而更加灵活。
但是,从理解的角度来看,
继承是“is a”的概念,即:鸟是动物,因而使用继承更加合理。
组合是“has a”的概念,即:鸟有羽毛,则使用组合更加合理,而使用继承就会变成羽毛继承鸟,不合理。