using System;
// Define an interface
interface IAnimal
{
// Interface members
string Name { get; set; }
void Speak();
}
// Implement the interface in the Dog class
class Dog : IAnimal
{
// Property implementation
public string Name { get; set; }
// Constructor
public Dog(string name)
{
Name = name;
}
// Method implementation
public void Speak()
{
Console.WriteLine($"{Name} says: Woof!");
}
}
// Implement the interface in the Cat class
class Cat : IAnimal
{
// Property implementation
public string Name { get; set; }
// Constructor
public Cat(string name)
{
Name = name;
}
// Method implementation
public void Speak()
{
Console.WriteLine($"{Name} says: Meow!");
}
}
class Program
{
static void Main()
{
// Create instances of Dog and Cat
IAnimal myDog = new Dog("Buddy");
IAnimal myCat = new Cat("Whiskers");
// Call the Speak method
myDog.Speak(); // Outputs: Buddy says: Woof!
myCat.Speak(); // Outputs: Whiskers says: Meow!
}
}
Abstraction: Interfaces allow you to define a contract that specifies what a class must accomplish without detailing how it should achieve those goals. This promotes a clear separation of concerns and facilitates abstraction in your code.
Multiple Inheritance: C# does not support multiple inheritance for classes; however, a class can implement multiple interfaces. This feature enables more flexible and modular designs.
Decoupling: Interfaces contribute to decoupling your code, making it more modular and easier to maintain. You can change the implementation of an interface without impacting the code that relies on it.
Polymorphism: Interfaces facilitate polymorphic behavior. Different classes can implement the same interface in various ways, allowing you to treat objects of these classes as instances of the interface type.