Monday, 29 January 2018

What are Interfaces in C# and Java? A Simple Explanation

In this lesson we would cover the following:
  1. What are Interfaces?
  2. When can an Interface be used?
  3. Interface implementation example in C#
  4. Summary on Interfaces
  5. Interview Questions


    What are Interfaces?
    An interface is a class that is marked with the Interface keyword. According to the C# programming guide, an interface contains definitions for a group of related functionalities.. Maybe I could correct this by saying that, 'an interface contains only definitions...'. This means that interfaces would not contain any implementation.

    When do we Need an Interface?
    Interface is use when you want a class to inherit from more than one base classes. this capability, where a sub class inherits from more than on parent is called Multiple Inheritance. This is  a feature in C++ but not in C#. Interface is a way to achieve multiple inheritance in C#.
    Interface is defined using the interface keywork

    Example of Interface in C#
    In the example below, there are two interfaces called IMovable and IParkable. The class Car is defined to  inherit from the two Interfaces.
    Notice the the Car Class implements the methods in the two interfaces
       
    
        public interface IMovable
        {
             bool Equals();
        }
    
        public interface IParkable
        {
            String Park();
        }
    
        public class Car : IMovable, IParkable
        {
            // Implementation of Imovable
            public bool Equals()
            {           
                    return false;
            }
    
            public String Park()
            {
                return "I need a garage";
            }
        }
    
    Summary on Interfaces
    1. Any class that implements an interface must also implement all the members of that interface.
    2. Interfaces can contain both methods and properties
    2. Interfaces cannot be instantiated directly.
    A class can implement more than one interface.