Interface - DotNet and DataBase

Wednesday, 1 August 2018

Interface



The interface looks similar to the class, but the methods and properties don't have the implementation.
In general, we create a class using the class keyword, in the same way, we create Interface using the keyword “interface”.

interface  IEmployee
{
  void Distance();
}
Interface members are public by default. We cannot have explicit access modifiers to them.
Means we cannot add public/private etc… to an interface member.
An interface cannot contain field members. That means declaring variables inside an interface is not possible.
interface  IEmployee
    {
        void IEmployee();
        int i;
    }
We will get an error mesaage like
Error      1             Interfaces cannot contain fields 
Error      1             Interfaces cannot contain constructors

An interface cannot have the implementation of its members itself, in the derived class, we have to override the method and implement.
.Netframework doesn't support multiple inheritance. But we can achieve multiple inheritance by using interface

Example:
using System;
namespace Interfaces
{  
    interface Area
    {
        void Distance(int distanceinmiles);
    }

    public class AreainKms:Area
    {
        public void Distance(int distance)
        {
            double Distanceinkms = distance / 1000;
            Console.WriteLine("The distance in kms is :" + Distanceinkms);            
        }       
    }
    public class Areainmiles : Area
    {
        public void Distance(int distance)
        {
            double Distanceinmiles = distance / 1609.34;
            Console.WriteLine("The distance in mils is :"+ Distanceinmiles);
        }       
    }
    class Program
    {
        static void Main(string[] args)
        {
            AreainKms dist = new AreainKms();
            dist.Distance(2000);
            Areainmiles distMiles = new Areainmiles();
            distMiles.Distance(2000);
            Console.Read();
        }
    }
}

interface Area has a method "Distance", "Area" is inherited by two classes "AreainKms" and "Areainmiles", but the implementation is different.


Result
The distance in km is: 2
The distance in mils is: 1.24274547329961





No comments:

Post a Comment

x

Get Updates On

Discussion updates

Straight Into Your INBOX!

Enter your email address to subscribe to this website and receive notifications of new posts by email.