C# Program to Implement Multiple Interfaces in the Same Class
Last Updated :
21 Oct, 2021
Like a class, Interface can have methods, properties, events, and indexers as its members. But interface will contain only the declaration of the members. The implementation of interface’s members will be given by the class that implements the interface implicitly or explicitly. C# allows that a single class can implement multiple interfaces at a time, and also define methods and variables in that interface.
Approach
1. To implement three interfaces along with some methods in all the interfaces in the same class follow the following steps:
2. Create three Interfaces named as firstinterface, secondinterface, and thirdinterface with the declaration of methods in it.
interface firstinterface
{
// Declaration of method
void myfun1();
}
3. Now we create a, Int_Class that will implement all these interfaces like this:
class Int_Class : firstinterface, secondinterface, thirdinterface
- After that in Int_Class, we define the definition of Method1, Method2, and Method3.
- Now, create the objects named obj1, obj2, obj3 of Int_class in the main function.
- After creating objects, call the methods by using the objects of Int_Class in the main function.
Example:
C#
using System;
interface firstinterface
{
void myfun1();
}
interface secondinterface
{
void myfun2();
}
interface thirdinterface
{
void myfun3();
}
class Int_Class : firstinterface, secondinterface, thirdinterface
{
public void myfun1()
{
Console.WriteLine( "Hello! i am method of firstinterface" );
}
public void myfun2()
{
Console.WriteLine( "Hello! i am method of secondinterface" );
}
public void myfun3()
{
Console.WriteLine( "Hello! i am method of thirdinterface" );
}
}
class GFG{
public static void Main(String[] args)
{
firstinterface obj1;
secondinterface obj2;
thirdinterface obj3;
obj1 = new Int_Class();
obj2 = new Int_Class();
obj3 = new Int_Class();
obj1.myfun1();
obj2.myfun2();
obj3.myfun3();
}
}
|
Output:
Hello! i am method of firstinterface
Hello! i am method of secondinterface
Hello! i am method of thirdinterface
Explanation: In the above code, first we create three interfaces named firstinterface, secondinterface, and thirdinterface along with one method in each interface named myfun1, myfun2, and myfun3. Now we create an Int_Class that will implement all these three interfaces. Now in the main function, we create three objects of Int_class, i.e., obj1, obj2, and obj3, and using these objects we will call the methods of firstinterface, secondinterface, and thirdinterface.
Share your thoughts in the comments
Please Login to comment...