Stage 4: Interface introduced
Stage 4: Interface introduced
Highlights:
The question is where to define or implement a behavior only for certain birds.
The solution is to use interfaces, which are prefixed with "I" and denote objects that support a certain behavior.
Interfaces are like pure abstract classes, meaning they only define a contract and not implementation.
The implementation will be provided by the specific child that adheres to the interface.
The "ISingable" interface is used for birds that can sing, and if a class doesn't implement it, there will be an error.
An example of a bird that doesn't implement the interface is the eagle, which cannot sing.
By having well-defined contracts, developers are prevented from using objects in ways they're not supposed to.
This provides an additional layer of robustness while keeping everything neat and understandable.
Animal.cs
No change!
Bird.cs
No change!
Cat.cs
No change!
Dog.cs
No change!
Eagle.cs
namespace MyApplication.Animals;
public class Eagle(string name) : Bird(name)
{
public override void Climb()
{
Console.WriteLine($"{Name} is climbing a tower...");
}
}
ISingable.cs
namespace MyApplication.Animals;
public interface ISingable //pure abstract class
{
void Sing();
}
Parrot.cs
namespace MyApplication.Animals;
public class Parrot(string name) : Bird(name), ISingable
{
public override void Climb()
{
Console.WriteLine($"{Name} is climbing on a tree!");
}
public void Sing()
{
Console.WriteLine($"{Name} is singing...");
}
}
Program.cs
using MyApplication.Animals;
var cat = new Cat("Tom");
Console.WriteLine($"{cat.Name} created!");
cat.Eat();
cat.Climb();
Console.WriteLine();
var dog = new Dog("Mike");
Console.WriteLine($"{dog.Name} created!");
dog.Eat();
dog.Climb();
Console.WriteLine();
// parrot can sing now!
var parrot = new Parrot("Glory");
Console.WriteLine($"{parrot.Name} created!");
parrot.Eat();
parrot.Climb();
parrot.Fly();
parrot.Sing();
Console.WriteLine();
//introducing eagle (cannot sing!)
var eagle = new Eagle("Jack");
Console.WriteLine($"{eagle.Name} created!");
eagle.Eat();
eagle.Climb();
eagle.Fly();
Console.WriteLine();
Last updated