in the previous article I explained how to declare and implement an interface.
In this article I am explaining how to inherit an interface by a class or interface. We will look here at how to inherit multiple interfaces on classes and use an interface type variable.
Example 1
How can an interface inherit another interface?
We can inherit an interface by another interface. For example we have two interfaces, one is "IVehicle" and another is "ICart". The IVehicle interface is inherited by the ICart interface and the ICart interface is inherited by the "Vehicle" class. So we need to implement methods of both IVehicle and ICart interfaces in Vehicle classes.
using System;
namespace InterfaceExamples
{
interface IVehicle
{
double Speed(int distance, int hours);
}
interface ICart :IVehicle
{
double CalculateDistance(double speed,int hours);
}
class Vehicle : ICart
{
public double Speed(int distance, int hours)
{
double speed = 0.0d;
speed = distance / hours;
return speed;
}
public double CalculateDistance(double speed, int hours)
{
double distance = 0.0d;
distance = speed * hours;
return distance;
}
}
class Program
{
static void Main(string[] args)
{
int distance =500,hours=2;
double speed,calDistance = 0.0;
Vehicle objVehicle = new Vehicle();
speed = objVehicle.Speed(distance, hours);
Console.WriteLine("speed is {0}", speed);
calDistance = objVehicle.CalculateDistance(speed, hours);
Console.WriteLine("calculated distance is {0}", distance);
Console.Read();
}
}
}

Example 2
Can a class inherit multiple interfaces?
Yes, a class or interface can inherit multiple interfaces. We have two interfaces "IVehicle" and "ICart". IVehicle has a "Speed()" method and ICart has a "CalculateDistance()" method. Both IVehicle and ICart interfaces are inherited by the "Vehicle" class so we implement methods of interfaces in the Vehicle class. If a class inherits more than one interface then each interface is separated by a comma (,).
using System;
namespace InterfaceExamples
{
interface IVehicle
{
double Speed(int distance, int hours);
}
interface ICart
{
double CalculateDistance(double speed,int hours);
}
class Vehicle : IVehicle, ICart
{
public double Speed(int distance, int hours)
{
double speed = 0.0d;
speed = distance / hours;
return speed;
}
public double CalculateDistance(double speed, int hours)
{
double distance = 0.0d;
distance = speed * hours;
return distance;
}
}




Rajeesh MenothPosted Jul 30, 2015, 3:01 AM
Good one