Interfaces

OOP: Interfaces

Concept of Interfaces:

An interface is a reference type that defines a contract for classes to implement certain behavior without specifying how that behavior should be implemented. Interfaces contain method and property declarations but no implementation details. Any class that implements an interface must provide implementations for all the members defined by that interface.

As per provided syntax on the OOP page, there is an interface called 'IAnimal' which defines two methods: 'Eat()' and 'Sleep()'. Any class that implements this interface must provide implementations for both of these methods.

interface IAnimal {
    void Eat();
    void Sleep();
}

Then, there's a class 'Dog' which implements the 'IAnimal' interface. This means that the 'Dog' class is required to provide implementations for both 'Eat()' and 'Sleep()' methods defined in the IAnimal interface.

class Circle : Shape {
    public override void Draw() {
        Console.WriteLine("Drawing a circle...");
    }
}

In the Dog class, both the 'Eat()' and 'Sleep()' methods are implemented with their respective behaviors for a dog.

Let's create a complete program:

cs Copy Code
using System;

interface IAnimal {
    void Eat();
    void Sleep();
}

class Dog : IAnimal {
    public void Eat() {
        Console.WriteLine("Dog is eating...");
    }

    public void Sleep() {
        Console.WriteLine("Dog is sleeping...");
    }
}

class Program {
    static void Main(string[] args) {
        Dog myDog = new Dog();
        myDog.Eat();
        myDog.Sleep();
    }
}
Output:
Dog is eating...
Dog is sleeping...

This demonstrates how the 'Dog' class implements the behavior specified by the 'IAnimal' interface.

Using interfaces allows for a high degree of flexibility and code reusability. For example, you can have multiple classes implementing the same interface, and you can treat objects of those classes uniformly through the interface type, enabling polymorphism and abstraction.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.