basic concepts:
- The Richter substitution principle was proposed in 1988 by a girl from the Massachusetts Institute of Technology.
- When inheriting, try not to override the parent class methods in the subclass
(for example: all the methods of class A are overridden by class B. Then why inherit? Just create a new class B directly) - The Richter substitution principle tells us that inheritance enhances the coupling of two classes , and solves problems through aggregation, composition, and dependency under appropriate circumstances.
What to do with Richter replacement:
Increase base class, reduce coupling
For example:
public class Liskov { public static void main(String[] args) { A a = new A(); System.out.println("11-3=" + a.func1(11, 3)); System.out.println("1-8=" + a.func1(1, 8)); System.out.println("-----------------------"); B b = new B(); System.out.println("11-3=" + b.func1(11, 3));//这里本意是求出11-3 System.out.println("1-8=" + b.func1(1, 8));// 1-8 System.out.println("11+3+9=" + b.func2(11, 3)); } } // A类 class A { // 返回两个数的差 public int func1(int num1, int num2) { return num1 - num2; } }
Pay attention to the fun1 method here. Programmer 1 accidentally re-parented the method, and the name may happen to be the same, resulting in the 11-3=14,1-9=9 requested above.
// B类继承了A // 增加了一个新功能:完成两个数相加,然后和9求和 class B extends A { //这里,重写了A类的方法, 可能是无意识 public int func1(int a, int b) { return a + b; } public int func2(int a, int b) { return func1(a, b) + 9; } }
Solution:
public class Liskov { public static void main(String[] args) { // TODO Auto-generated method stub A a = new A(); System.out.println("11-3=" + a.func1(11, 3)); System.out.println("1-8=" + a.func1(1, 8)); System.out.println("-----------------------"); B b = new B(); //因为B类不再继承A类,因此调用者,不会再func1是求减法 //调用完成的功能就会很明确 System.out.println("11+3=" + b.func1(11, 3));//这里本意是求出11+3 System.out.println("1+8=" + b.func1(1, 8));// 1+8 System.out.println("11+3+9=" + b.func2(11, 3)); //使用组合仍然可以使用到A类相关方法 System.out.println("11-3=" + b.func3(11, 3));// 这里本意是求出11-3 } } //创建一个更加基础的基类 class Base { //把更加基础的方法和成员写到Base类 } // A类 class A extends Base { // 返回两个数的差 public int func1(int num1, int num2) { return num1 - num2; } } // B类继承了A // 增加了一个新功能:完成两个数相加,然后和9求和 class B extends Base { //如果B需要使用A类的方法,使用组合关系 private A a = new A(); //这里,重写了A类的方法, 可能是无意识 public int func1(int a, int b) { return a + b; } public int func2(int a, int b) { return func1(a, b) + 9; } //我们仍然想使用A的方法 public int func3(int a, int b) { return this.a.func1(a, b); } }