Interface explained in easy steps

Interface is similar to a class but with only declaration and no definition. Below are few code to explain interface in easy steps.

Interface member can not have definition. They have only declaration.

interface ITest
{
void Method();
}

All members in interface are by default public. No need to add explicit access
modifier.

interface can not contain fields.
In below code int i; expression will throw compile time error.

interface ITest
{
int i;
void Method();
}

A class can inherit interface.
If you compile below code, it will throw error saying – MyClass does not implement

interface ITest.Method();
class MyClass:ITest
{

}

Interface allow multiple inheritance property.

interface ITest1
    {
        void Method1();
    }

    interface ITest2
    {
        void Medthod2();
    }

    class MyClass:ITest1, ITest2
    {

        public void Method1()
        {
             //Write code
        }

        public void Medthod2()
        {
           //write code
        }
    }

A class doesnt provide multiple inheritance.

public class Program:MyClass1, MyClass2
{

}

It will throw error class Program can not have multiple base classes.
So multiple class inheritance is not possible, but multiple interface inheritance is
possible.

Leave a Comment

RSS
YouTube
YouTube
Instagram