Stage 1: Inheritance

Stage 1: Inheritance

Highlights:

  • The previous stage implemented the animal's game but had a lot of repetitions violating the "do not repeat yourself" principle.

  • The "eat" function was the same in all animals, so it was removed from each animal and put in a parent "animal" class.

  • The "name" attribute was also made common to all animals in the "animal" class.

  • The program still had errors because the animals needed to inherit from the "animal" class and call its constructor.

  • The climb behavior is different for each animal, so it cannot be put in the "animal" class.

  • The next stage will cover removing similar but not same behaviors.

Animal.cs

namespace MyApplication.Animals;

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

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

Cat.cs

namespace MyApplication.Animals;

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

Dog.cs

namespace MyApplication.Animals;

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

Parrot.cs

namespace MyApplication.Animals;

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

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

Program.cs

No change!

Last updated