質問

Lets say we have this really 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);
    }
}

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

What about this one:

class B : A
{
    int variable;

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

As far as I understood the use of the variable "variable" causes a stronger pre-condition and therefore it violates the LSP. But i'm not completely sure how to follow the LSP when using Polymorphism.

役に立ちましたか?

解決

That's valid, in both cases it doesn't break the principle. B can be substituted for A. It just has different functionality.

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

他のヒント

From my understanding of it I would say that both your examples violate LSP as the subclass cannot be replaced by its superclass. Consider the following:

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

If you were to pass a reference to a B object into Foo the assert will fail. The B.Function is changing the poscondition of A.Function. The Foo client code shouldn't have to know about possible subtypes which may break their code.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top