DEV Community

Discussion on: C# | Virtual Methods

Collapse
 
jaywilkinson profile image
James Wilkinson

In the animal class wouldn't it be better to mark the MakeSound method abstract so any classes that derive from it must implement it

Collapse
 
hbolajraf profile image
Hassan BOLAJRAF • Edited

Yes, marking the MakeSound method as abstract in the Animal class would be a better approach if you intend for every derived class to provide its own specific implementation of the method. By doing so, you ensure that any subclass of Animal must override and provide a concrete implementation for MakeSound, enforcing a consistent behavior across all subclasses.

The implementation would be something like this:


public abstract class Animal
{
    public abstract void MakeSound();
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Dog barks");
    }
}

public class Cat : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Cat meows");
    }
}

class Program
{
    static void Main()
    {
        Animal myDog = new Dog();
        Animal myCat = new Cat();

        myDog.MakeSound();  // Output: Dog barks
        myCat.MakeSound();  // Output: Cat meows
    }
}
Enter fullscreen mode Exit fullscreen mode