组合: 类和类之间的关系,整体 和 局部的关系。
语法:
局部类作为 整体类的实例成员变量。
class 整体类{
局部类 对象 = new 局部类();
}
整体类 对象= new 整体类();
// 局部类
class Heart{
public void beat() {
System.out.println("心跳");
}
}
class Wolf1{
Heart heart = new Heart();
public void run() {
System.out.println("跑");
}
}
/*class Wolf1{
private Heart heart = new Heart();
public void beat() {
heart.beat();
}
public void run() {
System.out.println("跑");
}
}*/
public class TestAnimal2 {
public static void main(String[] args) {
Wolf1 wolf = new Wolf1();
wolf.heart.beat();
wolf.run();
}
}
组合相对继承的优点:不会对类产生有害的影响,比继承灵活,且减少了相对继承对父类的依赖。