Sobes.tech
Junior — Middle

Kas saaksite anda Liskovi asendamise põhimõtte näidet objektorienteeritud programmeerimises?

sobes.tech AI

Vastus AI-lt

The Liskov Substitution Principle (LSP) states that objects of a subclass should be replaceable with objects of the superclass without affecting the correctness of the program.

Example in C#:

class Bird {
    public virtual void Fly() {
        Console.WriteLine("Bird is flying");
    }
}

class Sparrow : Bird {
    public override void Fly() {
        Console.WriteLine("Sparrow is flying");
    }
}

class Ostrich : Bird {
    public override void Fly() {
        throw new NotSupportedException("Ostrich cannot fly");
    }
}

void MakeBirdFly(Bird bird) {
    bird.Fly();
}

// Usage:
MakeBirdFly(new Sparrow()); // correct
MakeBirdFly(new Ostrich()); // violates LSP, as it throws an exception

In this example, the Ostrich class violates the Liskov Substitution Principle because it does not support the behavior of the base class Bird (Fly method), throwing an exception instead. To adhere to LSP, the class hierarchy should be modified or interfaces split so that subclasses are not forced to implement unsupported behavior.