继承和组合 在框架复杂情况下的区别(案例)

继承的运用在这里简单阐述一下,主要讲组合的区别。
关于继承:先创一个person类,再创一个superMan类继承,子类有特有方法:超能力。
然后创建一个ZhiZhuXia(蜘蛛侠)类,一个BianFuXia(蝙蝠侠)类,两个类都继承superMan类,那么这两个大侠就有了普通人的属性方法,并且有了超人的特有方法:超能力。

好了下面开始讲讲组合的案例,现在需要的是有一个异能者,它触碰到什么超人就有什么超能力。
先看UML图:
继承和组合 在框架复杂情况下的区别(案例)

class Person {
	private int age=21;
	private String name="人";

	public int getAge() {
		return age;
	}
	public String getName() {
		return name;
	}
}

interface ISuperPower{
	public void superPower();
}


class YiNengZhe extends Person implements ISuperPower{
	protected ISuperPower isp;
	
	public void superPower() {
		isp.superPower();
		
	}

}

class BianFuXia extends YiNengZhe{
	public void superPower() {
		System.out.println("蝙蝠侠超能力!");
	}
}

class ZhiZhuXia extends YiNengZhe{
	public void superPower() {
		System.out.println("蜘蛛侠超能力!");
	}
}

public class Test3 {
	public static void main(String[] args) {
		YiNengZhe ynz=new YiNengZhe();
		ynz.isp=new ZhiZhuXia();
		ynz.superPower();
		ynz.isp=new BianFuXia();
		ynz.superPower();
	
	}
}

所以组合的优势在于,能够实现一个并不固定的某具体功能的类。也是通过继承和多态体现出来的。
可以说是用了组合+继承+多态。