里氏替换原则(Liskov Substitution Principle LSP)

    Liskov于1987年提出了一个关于继承的原则“Inheritance should ensure that any property proved about supertype objects also holds for subtype objects.”——“继承必须确保超类所拥有的性质在子类中仍然成立。”也就是说,当一个子类的实例应该能够替换任何其超类的实例时,它们之间才具有is-A关系。

    这里写图片描述

    public abstract class AbstractBird {
    
        protected String color;
        protected String name;
    
        public AbstractBird(String color, String name) {
            this.color = color;
            this.name = name;
        }
    
        public void show() {
            System.out.println("看那是" + this.name + ":颜色是" + this.color);
            drinking();
            goWalk();
            sleep();
        }
    
        public abstract void goWalk();
    
        public abstract void sleep();
    
        public abstract void drinking();
    }
    
    public class Zoo {
    
        private AbstractBird abstractBird;
    
        public Zoo(AbstractBird abstractBird) {
            this.abstractBird = abstractBird;
        }
    
        public void show() {
            this.abstractBird.drinking();
        }
    }
        public static void main(String[] args) {
    //      Zoo zoo = new Zoo(new Canary("红色", "金丝雀"));
            Zoo zoo = new Zoo(new Magpie("蓝色", "喜鹊"));
    //      Zoo zoo = new Zoo(new Sparrow("黑色","麻雀"));
            zoo.show();

    对象本身有一套对自身状态进行校验的检查条件,以确保该对象的本质不发生改变,这称之为不变式(Invariant)。

    public class Stone {
    
        public Number getNumber() {
            return new Integer(99);
        }
    }
    
    public class Adamas extends Stone {
    
        @Override
        public Integer getNumber(){
            return new Integer(22);
        }
    }
    public class StoneClient {
    
        public static void main(String[] args) {
            Stone stone = new Adamas();
            System.out.println(stone.getNumber());
        }
    }
    答案
    22
    
    如果把父类的参数缩小,子类的参数扩大,就问题出问题
    
    public class Stone {
    
        public Number getNumber(HashMap map) {
            return new Integer(99);
        }
    }
    public class Adamas extends Stone {
    
        public Number getNumber(Map map) {
            return new Integer(22);
        }
    }
    public class StoneClient {
    
        public static void main(String[] args) {
            //Stone stone = new Stone();
            Adamas stone = new Adamas();
            System.out.println(stone.getNumber(new HashMap()));
        }
    }
    答案 2个打印出都是99 ,我们想要的,9922

    总结就是子类的方法参数一定要小于等于父类的参数。

    • 0
      点赞
    • 0
      收藏
      觉得还不错? 一键收藏
    • 0
      评论
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值