示例已发推论
/** * @description: 示例引发里氏替换原则的实现 * @author: abel.he * @date: 2023-08-03 **/ public class Test1 { public static void main(String[] args) { Person person = new Person(); System.out.println("9 + 2 = " + person.calc(9, 2)); Child child = new Child(); // 这里本意是求出9+2 的和 System.out.println("9 + 2 = " + child.calc(9, 2)); } } class Person { public int calc(int a, int b) { return a + b; } } class Child extends Person { public int calc(int a, int b) { return a - b; } public int calc1(int a, int b) { return calc(a, b) + 9; } }
里氏替换原则优化
/** * @description: 里氏替换原则的实现 * @author: abel.he * @date: 2023-08-03 **/ public class Test1 { public static void main(String[] args) { Person person = new Person(); System.out.println("9 + 2 = " + person.calc(9, 2)); Child child = new Child(); // 这里本意是求出9+2 的和 System.out.println("9 - 2 = " + child.calc(9, 2)); System.out.println("9 + 2 = " + child.calc2(9, 2)); } } class Base { } class Person extends Base { public int calc(int a, int b) { return a + b; } } class Child extends Base { private Person person = new Person(); public int calc(int a, int b) { return a - b; } public int calc1(int a, int b) { return calc(a, b) + 9; } public int calc2(int a, int b) { return person.calc(a, b); } }
标签:设计模式,return,原则,int,里氏,class,Person,calc,public From: https://www.cnblogs.com/abel-he/p/17604682.html