先讲下继承:
优点:
缺点:
侵入性,降低灵活性,增强耦合性
解决继承的缺点:
里氏替换!
定义1:If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T,the behavior of P is unchanged when o1 is substituted for o2 then S is a subtypeof T.
(如果对每个类型为S的对象o1,都有类型为T的对象o2,使得以T定义的所有程序P在所有对象o1都代换成o2时,程序P的行为没有发生变化,那么类型S是T的子类型)
定义2:Functions that use pointers of references to base classes must be able to use objects of derived classes without kNowing it.
(所有引用基类的地方必须能透明地使用其子类对象)
包含了四层含义:
eg:
枪的职责:射击
士兵类:killEnemy,使用枪杀敌,具体用什么枪,调用的时候才知道
下面给出枪的抽象类:
- public abstract class AbstractGun
- {
- void shoot();
- }
手枪等枪的实现类:
- class Handgun extends AbstractGun
- //手枪
- @Override
- void shoot()
- {
- System.out.printIn("手枪射击");
- }
- }
- class Soldier
- private AbstractGun gun;
- void setGun(AbstractGun _gun)
- {
- this.gun=_gun;
- }
- void killEnemy()
- system.out.printIn("杀敌");
- gun.shoot();
- }