Skip to main content

Interface with real life Examples


Interfaces with real life examples


An interface is a programming structure/syntax that allows the computer to enforce certain properties on an object (class). For example, say we have a car class and a tricyclic class and a truck class. Each of these three classes should have a start engine() action. How the "engine is started" for each vehicle is left to each particular class, but the fact that they must have a start engine action is the domain of the interface.

The syntax of an Interface

We can implement single interface or multiple interfaces to the class. By default interfaces are public.
We declare interface by using "interface" keyword.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CsharpnaijaInterfaceTutorial
{
    interface IEngine
    {
        void Start();
    }
}
Inside the {} of the interface is a list of functions that must be found in any object that implements the interface in this Start().

Implementation


    public class Car : IEngine
    {
        public void Start()
        {
            Console.Write("Car Started.");
        }
    }

   



    public class Truck : IEngine
    {
        public void Start()
        {
            Console.Write("Truck Started.");
        }
    }

    public class Tricyclic : IEngine
    {
        public void Start()
        {
            Console.Write("Tricyclic Started.");
        }
    }




From the above code snippets, we ca see that an Interface IEngine provides a contract that any other class that will implement the interface must a method implementation of the method signature provided by the interface.

The Car, Truck and Tricyclic classes implement the IEngine interface and provide different implementation for the method signature.

Let’s now see how to use the classes in our application

using System;

namespace InterfaceTutorial
{
    class Program
    {
        static void Main(string[] args)
        {
            var car = new Car();
            var truck = new Truck();
            var tricyclic = new Tricyclic();

            Console.WriteLine("Below are the Implementations of Start method for different vehicle");

            Console.WriteLine();
            car.Start();
            Console.WriteLine();
            truck.Start();
            Console.WriteLine();
            tricyclic.Start();
            Console.WriteLine();

            Console.ReadLine();
        }
    }
}




From the above code, we see that instances of Car, Truck and Tricyclic respectively and also called the start method of individual instance to print their start status to the console as shown below.


Another real life example of an interface

using System;
namespace InterfaceTutorial
{
    interface IAccount
    {
        void Deposit();
        void Withdraw();
    }

    public class Saving : IAccount
    {
        public void Deposit()
        {
            Console.WriteLine("Deposit to Saving Account");
        }

        public void Withdraw()
        {
            Console.WriteLine("Withdraw from Saving Account");
        }
    }
    public class Current : IAccount
    {
        public void Deposit()
        {
            Console.WriteLine("Deposit to Current Account");
        }

        public void Withdraw()
        {
            Console.WriteLine("Withdraw from Current Account");
        }
    }
}

In banking system in Nigeria we have Saving, Current, Fixed Deposit etc Accounts

To model this scenario, we create an interface of Account with the type of operations we want e.g. Deposit and Withdrawal such that Deposit and Withdraw are method signatures in the IAccount interface for any class to provide the implementation based on the account needed as modelled in the above code.

Benefits of using an interface
Below are some of the importance of using interfaces in our codes
o   Implemented interface enforces the class like a standard contract to provide all implementation of interface members.
o   In architecting the project we can define the proper naming conventions of methods, properties in an interface so that while implementing in a class we use the name conventions.
o   We can use the "interface" as a pointer in the different layers of applications.
o   We can use an interface for implementing run time polymorphism.

The two ways of implementing interfaces are

Explicit and Implicit
Explicit implementation

To implement an interface explicitly we have to define an interface name followed by (".") dot operator then the method name.

For example

        public void IEngine.Start()
        {
            Console.Write("Truck Started.");
        }
 We use explicit implementation of interface when we have two different interfaces with same method name.

Implicit implementation

To implement an interface implicitly, we have to implement the interface name after the class name using colon ":" operator as shown in below snipped code.
For example

    public class Truck : IEngine
    {
        public void Start()
        {
            Console.Write("Truck Started.");
        }
    }
An interface has the following properties:
·         An interface is like an abstract base class with only abstract members. Any class or struct that implements the interface must implement all its members.
·         An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface.
·         Interfaces can contain events, indexers, methods, and properties.
·         Interfaces contain no implementation of methods (but in C# 8.0, Interfaces can have default implementation for methods).
·         A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.

Comments

  1. This Interface will be helpful & useful to both Students & their lecturers. Thank u.

    ReplyDelete
  2. Your true color has started coming out as a DEVELOPER.
    Who say Marriage is NOT Good

    ReplyDelete
  3. I adore your work and expect online learning platform for people to register and take a course from you.

    ReplyDelete
    Replies
    1. Yes, that is already on the pipeline

      Delete
    2. I already have course for beginners to learn software development

      Delete
  4. This is first of its kind in teaching C#, especially that it's coming from a Nigerian.✌️

    ReplyDelete

Post a Comment

Popular posts from this blog

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

Most Popular Programming Languages in 2020

Most Popular Programming Languages in 2020 In this blog post, you will learn about the most popular programming languages in 2020 for creating the best web applications. Check its pros and cons. Analyzed by technostacks Not very long ago, just a few people were considered to be computer programmers, and the general public viewed them with awe. In this digital age that we are now living in, however, a large number of IT jobs need a solid grasp of one or more programming languages. Whether one wants to develop a mobile app or get a certification for having programming knowledge, or even to learn new skills, one needs to opt for the right programming language. Below mentioned eight most popular programming languages which are in demand for software development and web applications. This is the most used programming languages in 2019 and will be in 2020. For each, there is little information about the language, benefits and its complexity, as well as about its usage. One must...

HashTable in C# with Example

  HashTable in C# with Example Hashtable  is used to store a collection of key/value pairs of different  data types  and are organized based on the hash code of the key.   Generally, the hashtable object will contain buckets to store elements of the collection. The bucket here, is a virtual subgroup of elements within the hashtable and each bucket is associated with a hash code, which is generated based on the key of an element.   In C#, hashtable is same as a  dictionary  object but the only difference is that the  dictionary  object is used to store a key-value pair of same  data type  elements.   When compared with  dictionary  object, the hashtable will provide a lower performance because the hashtable elements are of object type so the boxing and unboxing process will occur when we are storing or retrieving values from the hashtable.   C# HashTable Declaration Hashtable is a non-generic type...