The Liskov Substitution Principle - An Example of Overriding

Suppose we have trivial classes:

class A
{
    virtual int Function(int number)
    {
      return number;
    }
}

class B : A
{
    override int Function(int number)
    {
        return number + 1;
    }
}

class UseExample
{
    void Foo(A obj)
    {
        A.Function(1);
    }
}

Will this example be a violation of LSP ?. If so, could you give me an example that does not violate the principle and uses a different implementation?

How about this:

class B : A
{
    int variable;

    override int Function(int number)
    {
        return number + variable;
    }
}

As I understand it, using the variable "variable" raises a stronger precondition and therefore violates the LSP. But I'm not quite sure how to follow LSP when using polymorphism.

+5
source share
2 answers

This is true, in both cases it does not violate the principle. B can be replaced by A. It has only different functionality.

an easy way to break a contract would be to throw an exception in Bs if the number == 23 or something :)

+2

, LSP, . :

class UseExample {
    void Foo(A& obj, int number) {
        int retNumber = obj.Function(number);
        assert(retNumber==number);
    }
}

B Foo, . B.Function A.Function. Foo , .

0

All Articles