Home > Articles > C# Articles > What is Interface and Abstract Class in c# ?

What is Interface and Abstract Class in c# ?

by Bikesh Srivastava   on Oct 03, 2016   Category: C#  | Level: Beginner  |  Views: 814    |  Points: 100   
Like this article? Bookmark and Share:
In this article we will learn What is Interface and Abstract Class in c# ? ,also learn differences between interfaces and abstract class with real example.

Abstract Class:-
An Abstract class is an incomplete class or this class we can't instantiate. We can use an Abstract class as a Base Class. An Abstract method must be implemented in the non-Abstract class(derived class) using the override keyword after inherit.
The purpose(use) of an abstract class is to provide basic or default functionality as well as common functionality that multiple derived classes can share and override in application.
Example:-How to use abstract class in c# ?
using System;
namespace abstractClass
{
    //Abstract class
    abstract class Shape1
    {
        //declaring varables.
        protected float R, L, B;
        //Abstract methods can have only declarations
        public abstract float Area();
        public abstract float Circumference();
        //Declaring non abstract method;
        public void Show()
        {
            Console.WriteLine("Non-Abstract method!");
        }
    }
    class Rectangle1 : Shape1 //implimenting abstarct class 
    {
        public void GetLB()
        {
            Console.Write("Enter  Length  :  ");

            L = float.Parse(Console.ReadLine());

            Console.Write("Enter Breadth : ");

            B = float.Parse(Console.ReadLine());
        }
        public override float Area()
        {
            return L * B;
        }
        public override float Circumference()
        {
            return 2 * (L + B);
        }
    }
    class Circle1 : Shape1 //implimenting abstarct class 
    {
        public void GetRadius()
        {
            Console.Write("Enter  Radius  :  ");
            R = float.Parse(Console.ReadLine());
        }
        public override float Area()
        {
            return 3.14F * R * R;
        }
        public override float Circumference()
        {
            return 2 * 3.14F * R;
        }
    }
    class MainClass
    {
        public static void Calculate(Shape1 S)
        {
            Console.WriteLine("Area : {0}", S.Area());
            Console.WriteLine("Circumference : {0}", S.Circumference());
            Console.WriteLine();
            S.Show();
        }
        static void Main()
        {
            //calling 
            Rectangle1 R = new Rectangle1();
            R.GetLB();
            Calculate(R);

            Console.WriteLine();
            //calling 
            Circle1 C = new Circle1();
            C.GetRadius();
            Calculate(C);

            Console.Read();
        }
    }

}
Output:-Run your console application using F5 and output is

Enter Length : 2 //press enter
Enter Breadth : 4 //press enter
Area : 8
Circumference : 12

Non-Abstract method!

Enter Radius : 12 
//press enter
Area : 452.16   

Circumference :75.36

Non-Abstract method!

Important points of abstract Class:-

1. An abstract class cannot be instantiated(can't create object).



2. An abstract class contain abstract members as well as non-abstract members(Both).

3. An abstract class does't be a sealed class because the sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.

4. A non-abstract class which is derived from an abstract class must include actual implementations of all the abstract members of base abstract class.

5. An abstract class can be inherited from a class and one or more interfaces.

6. An Abstract class can has access modifiers like private, protected, internal with class members. But abstract members cannot have private access modifier.

7. An Abstract class can has instance variables (like constants and fields).

8. An abstract class can has constructors and destructor.(~)

9. An abstract method is implicitly a virtual method (by default).

10. Abstract properties behave like abstract methods.

11. An abstract class cannot be inherited by structures(structs).

12. An abstract class cannot support multiple inheritance(due to ambiguity problem) .

Interfaces:-
An interface looks like a class, but interface  has no implementation . The only thing it contains are declarations of events, indexers, methods and/or properties. The reason interfaces only provide declarations is because they are inherited by structs and classes, that must provide an implementation for each interface member declared inside derived class.
Types of Interface implementation:-
1:-Implicit implementation
  1. All Members are public by default.
  2. All Members must be marked as public.
  3. All Members can be invoked directly through the object of the implementing class.
2:-Explicit implementation
  1. All Members are private by default.
  2. All Members can't have any access modifiers.
  3. All Members can't be accessed directly, an object of the implementing class should be cast to the Interface type to access the members.
Example:-How to use interface in c# ?
using System;
interface IValue
{
    int Count { get; set; } // Property interface.
    string Name { get; set; } // Property interface.
    void Show();
}
interface IData
{
    void Show();
}
class Image : IValue,IData // Implements interface.
{
    public int Count // Property implementation.
    {
        get;
        set;
    }
    string _name;
    public string Name // Property implementation.
    {
        get { return this._name; }
        set { this._name = value; }
    }
    void IData.Show() //Explicit  Implementation
    {
        Console.WriteLine("test function for Explicit  Implementation of IData Image Class");
    }
   public  void Show() // Implicit Implementation
    {
        Console.WriteLine("test function for interfaces Implicit Implementation Image Class");
    }
}
class Program
{
    static void Main()
    {
        //Calling of interfaces 1st way...
        IValue value1 = new Image();
        IData value2 = new Image();
        value1.Count++;
        value1.Name = "Bikesh Srivastava";
        Console.WriteLine(value1.Count);
        Console.WriteLine(value1.Name);
        value1.Show();         
        value2.Show();
        Console.WriteLine("==================================================");
        //Calling of interfaces 2nd way...
        Image img = new Image();
        img.Count++;
        img.Name = "Alok srivastava";
        Console.WriteLine(img.Count);
        Console.WriteLine(img.Name);
        img.Show();
        Console.WriteLine("==================================================");
        //Calling of interfaces 3nd way...
        IData da = (IData)img;
        IValue va = (IValue)img;       
        va.Count++;
        va.Name = "Bikesh Kumar";
        Console.WriteLine(va.Count);
        Console.WriteLine(va.Name);
        da.Show();
        Console.Read();
    }
}
Output:-Run your console application using F5 and output is
Interface output

Important points of interface:-

1.An Interface is a way to achieve runtime polymorphism(overriding polymorphism) in C#.

2.An Interface is a collection of properties and methods declarations in c#.

3.An Interface is a type declaration like a class or structure in C#; an Interface itself does not implement members.

4.All Interface like as  contract templates in which the contract members are declared in c#.

5.By default interfaces member modifier is Public .

6.Can't create instance of interfaces always implement inside derived classes .

7.we can't inherit multiple class at a time in a single class but interfaces can inherit multiple at a time.

8. we can't declare field inside interface but properties,indexer  can.

9.For good naming convention start interface name  always with I (Idemo).

Purposes of Interfaces in c# application :-


1.
Create loosely coupled software (application) in c#.

2.Support design by contract (an implementer must provide the entire interface).

3.Allow for pluggable software (application) in c#.

4.Allow objects to interact easily with other.

5.Hide implementation details of classes from each other in c# programming .

6.Facilitate reuse of software (application,logic) in c#.

Difference between abstract class and interface c#:-
Feature
Interface
Abstract class
Multiple inheritance
A class can inherit multiple interfaces.
A class can inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature in c#.
An abstract class can provide complete, default code and/or just the details that have to be overridden in derived class.
Access Modfiers
An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public in c#
An abstract class can contain access modifiers for the subs, functions, properties in c#
Inheritance 
you should implement all function inside derived classNo need to implement all (optional)
Homogeneity
If various implementations only share method signatures then it is better to use Interfaces in c#.
If various implementations are of the same kind and use common behavior or status then abstract class is better to use in c# application.
Speed
Requires more time to find the actual method in the corresponding classes in interfaces.
Fast as compare interface in c#
Adding functionality (Versioning)
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants
No fields can be defined in inside interfaces in c#
An abstract class can have fields and constants defined in c#



Like this article? Bookmark and Share:

Most viewed Articles

User Comments


No response found, be the first to review this article.

Submit feedback about this article

Please sign in to post feedback

Latest Posts