基本介绍
例子
B在无意的情况下重写了A类的func1方法,使得调用的时候使用的是自己所写的方法,破坏了原来的功能。
- 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));
- }
- }
-
- class A {
- //返回两个数的差
- public int func1 (int num1, int num2) {
- return num1 - num2;
- }
- }
-
- class B extends A {
- //返回两个数的差,无意的重写了父类的方法
- public int func1(int a, int b) {
- return a + b;
- }
- public int func2(int a, int b) {
- return func1(a, b) + 9;
- }
- }
运行结果

分析
例子改进
- 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();
- //因此此时B不再继承A类,所以不会再认为func1是求减法的
- //调用完成的功能会很明确
- System.out.println("11+3=" + b.func1(11, 3));
- System.out.println("1+8=" + b.func1(1, 8));
- System.out.println("11+3+9=" + b.func2(11, 3));
- //使用组合仍然可以使用A类相关方法
- System.out.println("11-3="+b.func3(11,3));
- }
- }
- //基类
- class Base {
- //把更加基础的方法和成员写到Base类
- }
- class A extends Base{
- //返回两个数的差
- public int func1 (int num1, int num2) {
- return num1 - num2;
- }
- }
-
- class B extends Base {
- public A a = new A();
- //返回两个数的差,无意的重写了父类的方法
- public int func1(int a, int b) {
- return a + b;
- }
- public int func2(int a, int b) {
- return func1(a, b) + 9;
- }
- public int func3(int a, int b) { return this.a.func1(a, b);}
- }
运行结果

UML类图
