Sunday, June 2, 2013

Interface Inheritance

Similar to class inheritance, interfaces also support inheritance, an interface can inherit from another interface. Similar to class inheritance, interface inheritance also makes use of the (:) operator to define inheritance.

The following example defines a parent interface IVehicle, and a child interface IBus, the IBus interface inherits from the IVehicle interface.
    interface IVehicle
    {
        string GetNumber();
    }
    //
    interface IBus : IVehicle
    {
        string GetSeatingCapacity();
    }
    //
    class BusClass : IBus
    {
        public string GetNumber()
        {
            return "test";
        }
        //
        public string GetSeatingCapacity()
        {
            return "test";
        }
    }

The class BusClass implements the interface IBus and defines the methods GetNumber() which is defined in the parent interface and the method GetSeatingCapacity() which is defined in the child interface.
When a class implements a child interface it should define the methods and properties which are declared in both the parent and child interfaces, failing which will lead to an error as follows.

    interface IVehicle
    {
        string GetNumber();
    }
    //
    interface IBus : IVehicle
    {
        string GetSeatingCapacity();
    }
    //
    class BusClass : IBus
    {
        public string GetSeatingCapacity()
        {
            return "test";
        }
    }

Here the class BusClass defines the method in the child interface, but does not define the method from the parent interface IVehicle, hence the following error.

BusClass does not implement interface member IVehicle.GetNumber()

Search Flipkart Products:
Flipkart.com

No comments: