Thursday, 28 February 2013

Interfaces

  • This is also a user defined type same as a class but can contain only abstract members in it.
  • The abstract members of an Interface will be implemented by a child class of  the Interface so here also the Interface is imposing restrictions on the child class.
  • A child can be inherited either from another class or an Interface also. When a class is inheriting from another class it can inherit only from one class (Single Inheritance). When class is inheriting from an Interface it can be inherited from any number of interfaces (Multiple Inheritance).
  •  Inheritance is divided into two categories
  1.   Implementation Inheritance
  2.   Interface Inheritance
  • If a class is inheriting from another class we call it as implementation Inheritance and this provides reusibility because child classes can consume their parent class members.
  • If a class is inheriting from an Interface we call it as Interface Inheritance but Interface Inheritance does not provide any reusibility because here the child c lass is only implementing the methods of its parent Interface.
Syntax:
[<modifiers>]  Interface <Name>    
{
 Abstract class declaration
}   

Rules while working with Interfaces
  • We can not declare variables under an interface.
  • Default scope for a member of an Interface is public where as it is private in case of class.
  • Every member of an Interface is by default abstract so we don't require to declare explicitly.
  • An Interface can inherit from another Interface if required.
Add an Interface item template under the project by choosing Interface from the add new item window and name it interface1.cs

interface Interface1
    {
        void add(int x, int y);
        void sub(int x, int y);
    }

Add another interface interface2.cs and write the following code

interface Interface2
    {
        void mul(int x, int y);
        void div(int x, int y);
    }

Now to implement the members of both these interfaces add a class interclass.cs and write the following code
       
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApps
{
    class interclass: Interface1,Interface2
    {
        public void add(int x, int y)
        {
            Console.WriteLine(x + y);
        }
        public void sub(int x, int y)
        {
            Console.WriteLine(x - y);
        }
        public void mul(int x, int y)
        {
            Console.WriteLine(x * y);
        }
        public void div(int x, int y)
        {
            Console.WriteLine(x / y);
        }
        static void Main()
        {
            interclass c = new interclass();
            c.add(100,45);
            c.sub(89,26);
            c.mul(12,34);
            c.div(456,23);
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment