Saturday, May 2, 2015

Advantage of abstract class over Interface in C#.Net

Advantage of abstract class over interface in C# is, If you want to have additional functionality for the interface, you must implement the new ones in all of the classes that implement the changed interface. The code will not work until you make the change. But if you want to have additional functions to the Abstract class, you can have default implementation. Your code still might work without many changes.

For e.g: Suppose we have interface ITest having DoTask() method, and both ClassA & Class B is derived from ITest interface and implementing DoTask method of Interface.

interface ITest
    {
        void DoTask();
    }

    public class ClassA : ITest
    {
        public void DoTask()
        {
            int a;
        }
    }
    
    public class ClassB : ITest
    {
        public void DoTask()
        {
            int a;
        }
    }

Code will work fine.

Now, suppose if we add one more method (DOWork) into interface ITest, then all the child classes (A & B) which are derived from ITest interface must implement new method, otherwise it will give following error,

Advantage of abstract class over Interface

Now check same example with abstract class, it will not give error like above,

//abstract class with abstract method, and its implementation in both derived classes.
    abstract class AbsClass
    {
        void DoTask();
    }

    public class ClassA : AbsClass
    {
        public void DoTask()
        {
            int a;
        }
    }
    
    public class ClassB : AbsClass
    {
        public void DoTask()
        {
            int a;
        }
    }

Now If we add default method (method with default implementation) in abstract class DoWork(), then no need to add method implementation to its all derived classes.

public abstract class AbsClass
    {
        // abstract method
        public abstract void DoTask();

        //Non- abstract method
        void DoWork()
        {
            int a;
        }
    }

    public class ClassA : AbsClass
    {
        public override void DoTask()
        {
            int a;
        }
    }

    public class ClassB : AbsClass
    {
        public override void DoTask()
        {
            int a;
        }
    }

In short Advantage of abstract class over interface is we can easily add new default implemented method to existing abstract class and no need to implement that method in all the child classes.
But if we add new method to existing interface then we need to implement that method in every derived classes.

No comments:

Post a Comment