Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Experts,

While I reading some blog I read one approach that is used by someone in interface and abstract class but I am not clearly understand that Please help me to find out that.

1)What are benefits of inheriting the interface in abstract class?when we go for this approach?Is it good practice to doing that? Is this really a duplicate of code in both place?

e.g
C#
public interface IService
    {
        void Add();
        void Mul();
    }
    //First Case
    public abstract class ServiceOne : IService
    {
        public abstract void Add();
        public abstract void Mul();
    }
    //Second Case
    public abstract class ServiceTwo : IService
    {
        public void Add(){}
        public void Mul(){}
    }

    public class S1 : ServiceOne
    {
        public override void Add(){}
        public override void Mul() {}
    }
    public class S2 : ServiceTwo
    { }



So in above example we have a IService interface and having two method add() and mul().And Same method is inheriting in (Case 1) abstract class Serviceone and again its abstract method here in (case 2) inheriting in abstract class ServiceTwo but provide the implementation of interface method.


Thanks
Dinesh

What I have tried:

C#
What are basic benefits of doing that duplication of code in interface and abstract class.
Posted
Updated 13-Dec-16 22:29pm
Comments
[no name] 13-Dec-16 20:26pm    
There is no duplicate. Interfaces do not contain code. The interface is a contract not an implementation.
Er. Dinesh Sharma 13-Dec-16 20:34pm    
When we need this approach same method in interface and same in abstract class that inherited it.

If the abstract classes merely reproduce the signature of the interface (as in your scenario) then it is nearly useless. Generally speaking, the abstract class does augment interface signature or provide some implementation. Such features make it useful.
 
Share this answer
 
I wouldn't do such a thing unless IService was already defined and used elsewhere for some other purpose. If you want to take an existing interface and make an abstract class implement it that is fine I guess. As mentioned already though, if the interface is defined solely for the purpose of defining the methods of the abstract class then it's pointless. The only caveat to that might be if you were only interested in a sub-set of methods somewhere. So IService might have "Add" and "Delete" but the abstract class might also have "Sort", "Reverse" etc, and you might have other classes that are only interested in objects that use "Add" and "Delete" so you could pass objects that implement IService to that object.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900