Wednesday 9 May 2012

Basic of Interface


For Asp.net Training with C# Click Here

Written By:-Isha Malhotra
Email:-malhotra.isha3388@gmail.com

Basic of Interface
Interface is an entity which gives signature or a structure which class have to implement. It contains only declaration not definition. The class which implement the interface will give the definition to each member. It means we can only declare the method, property and event.
Simply interface is ‘what’ should be done and its implementation is ‘how’ it should be done.
Note:-1. All members of the Interface declared without access specifier like public, private etc.
2. We cannot declare any variable in interface.
3. All members should be implemented in the derived class.


Example:-
Steps for interface
1.     Open visual studio->new->web application
2.     Add class and delete all code regarding class.
3.     Declare the interface like:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public interface idef
{
   
     int sum(int p, int q);
     int mul(int p, int q);
}

4.     Add another class for implementing the interface. And implement all the method declared in the interface like:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Class2
/// </summary>
public class Class2: idef
{

    public int sum(int x, int y)
    {

        return x + y;

    }

   public int mul(int x, int y)
    {

        return x * y;

   
    }

}

5.     On page load call these methods which is declared in the interface and implemented in the class2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // create the object of class which implement interface
        Class2 cl = new Class2();

        Label1.Text = Convert.ToString(cl.sum(4, 5));
        Label2.Text = Convert.ToString(cl.mul(4, 5));
    }
}

This is the basic implementation of interface.



No comments:

Post a Comment