In this article, we will be discuss what an interface is and how to easily implement an inheritance in it. First we look at what an Interface is.
- An interface is a way to define a set of methods that we implement by a derived class or multiple derived classes.
- Two classes can implement the same interface in a different way.
- It is basically a logical structure that describes the functionality (methods) but not its implementation( body).
- A class must provide the bodies of the methods described in an interface to implement the methods.
We can declare an interface in the following way:
interface name {
return-type method-name1( parameter list);
return-type method-name2( parameter list);
}
We declare an interface with the keyword interface. Here "name" is the name of the interface. In an interface all the methods are public, so there is no requirement for explicit access specifiers.
Example
Here ICalc is the name of the interface and add and sub is the methods of the interface.
Now we implement an interface in the following way:
class class-name:interface-name{
// body of the class }
A class can implement more than one interface. We can declare each interface in a comma-separated list. In this case, the name of the base class is always first.
Example
The output will be:
The Addition is:5
The Subtraction is:1
Complete Program
using System;
public interface ICalc
{
int add(int a,int b);
int sub(int x,int y);
}
class Calc:ICalc
{
public int add(int a,int b)
{
return a+b;
}
public int sub(int x,int y)
{
return x-y;
}
}
class MainCalc
{
Calc c=new Clac();
Console.WriteLine("The Addition Is:" + c.add(2,3));
Console.WriteLine("The Subtraction Is:" + c.sub(3,2));
}
Inheritance in the Interfaces
Interfaces can be inherited. Now we look at the example of how to easily inherit an interface:
After inheritance, "second" has the methods of the first interface and it adds printC() to it. Now the class MyClass can access all the three methods:
Complete Program
using System;
public interface first
{
void printA();
void printB();
}
public interface second:first
{
void printC();
}
class MyClass:second
{
public void printA()
{
Console.WriteLine(" Print A");
}
public void printB()
{
Console.WriteLine(" Print B");
}
public void printC()
{
Console.WriteLine(" Print C");
}
}
class MyMainClass
{
public static void main()
{
MyClass a=new MyClass();
a.printA();
a.printB();
a.printC();
}
}