I am reading a book about Design Patterns, and there's this chapter on the Liskov Substitution Principle that says to do this (and other tasks) to achieve the principle:
Parameter types in a method of a subclass should match or be more abstract than parameter types in the method of the superclass. Sounds confusing? Let’s have an example.
Say there’s a class with a method that’s supposed to feed cats: feed(Cat c).
Client code always passes cat objects into this method.
◦ Good: Say you created a subclass that overrode the method so that it can feed any animal (a superclass of cats): feed(Animal c). Now if you pass an object of this subclass instead of an object of the superclass to the client code, everything would still work fine. The method can feed all animals, so it can still feed any cat passed by the client.
◦ Bad: You created another subclass and restricted the feed- ing method to only accept Bengal cats (a subclass of cats): feed(BengalCat c). What will happen to the client code if you link it with an object like this instead of with the orig- inal class? Since the method can only feed a specific breed of cats, it won’t serve generic cats passed by the client, breaking all related functionality.
To me everything seemed fine, till I decided to try implement this example in C#.
This is the code I wrote to understand better the "Good" part of the example:
public class Animal { }
public class Cat : Animal { }
public class AnimalFeeder
{
public virtual void Feed(Cat c)
{
Console.WriteLine("Feeding a cat...");
}
}
public class GenericFeeder : AnimalFeeder
{
public override void Feed(Animal a) // Compile Error - No suitable method found to override
{
Console.WriteLine("Feeding an animal...");
}
}
The only problem is that I get the error above,
maybe I misunderstood the example and didn't wrote the correct code,
if yes can someone help me correct the code in the proper way?
Thank you in advance!