package principle.liskov; /** * @author wxy * @description Richter's substitution principle simple Edition * @data 2020/6/28 */ 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(); System.out.println("11-3=" + b.func1(11, 3));//The original idea here is to find 11-3 System.out.println("1-8=" + b.func1(1, 8));// 1-8 System.out.println("11+3+9=" + b.func2(11, 3)); } } // Class A class A { // Returns the difference between two numbers public int func1(int num1, int num2) { return num1 - num2; } } //Class B inherits A //Added a new function: complete the addition of two numbers, and then sum 9 class B extends A { //Here, the class A method is rewritten, which may be unconscious @Override public int func1(int a, int b) { return a + b; } public int func2(int a, int b) { return func1(a, b) + 9; } }
package principle.liskov.improve; /** * @author wxy * @description Richter's principle of substitution * @data 2020/6/28 */ 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(); //Because class B no longer inherits class A, the caller will no longer be subtracting func1 //The function completed by the call will be clear System.out.println("11+3=" + b.func1(11, 3));//The original idea here is to find 11 + 3 System.out.println("11+3+9=" + b.func2(11, 3)); //The combination can still be used for class A related methods System.out.println("11-3=" + b.func3(11, 3));// The original idea here is to find 11-3 } } //Create a more basic base class class Base { //Write more basic methods and members to the Base class } // Class A class A extends Base { // Returns the difference between two numbers public int func1(int num1, int num2) { return num1 - num2; } } // Class B inherits A // Added a new function: complete the addition of two numbers, and then sum 9 class B extends Base { //If B needs to use class A method, use combination relationship private A a = new A(); //Here, the class A method is rewritten, which may be unconscious public int func1(int a, int b) { return a + b; } public int func2(int a, int b) { return func1(a, b) + 9; } //We still want to use the A method public int func3(int a, int b) { return this.a.func1(a, b); } }