Stage 2: Abstract method

Stage 2: Abstract method

Highlights:

  • This stage shows how to adhere to the dry principle and eliminate repetitions in a program.

  • A common animal class is created to push all commonalities upward and remove them in individual child classes.

  • Polymorphism is used to deal with similar but not same behaviors.

  • An abstract method called "climb" is created as a contract that all other children of the animal should follow.

  • Child classes are required to override the climb method to implement it.

  • This implementation of polymorphism makes the code more flexible, extensible, and maintainable.

  • The program's output remains the same, and there are no errors.

Animal.cs

namespace MyApplication.Animals;

public abstract class Animal(string name)
{
    public string Name { get; } = name;

    public void Eat()
    {
        Console.WriteLine($"{Name} is eating...");
    }

    public abstract void Climb();
}

Cat.cs

namespace MyApplication.Animals;

public class Cat(string name) : Animal(name)
{  
    public override void Climb()
    {
        Console.WriteLine($"{Name} is climbing on a roof!");
    }
}

Dog.cs

namespace MyApplication.Animals;

public class Dog(string name) : Animal(name)
{
    public override void Climb()
    {
        Console.WriteLine($"{Name} is climbing on steps!");
    }
}

Parrot.cs

namespace MyApplication.Animals;

public class Parrot(string name) : Animal(name)
{
    public override void Climb()
    {
        Console.WriteLine($"{Name} is climbing on a tree!");
    }

    public void Fly()
    {
        Console.WriteLine($"{Name} is Flying!");
    }
}

Program.cs

No change!

Last updated