Coffeehouse Thread

60 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Abstract class vs Interface -When to use them and which scenario

Back to Forum: Coffeehouse
  • User profile image
    Surendiran Bala

    Hi

    I know how to use both Abstract class and interface in C#

    but i just want to know the what is the problem in using Abstract in place of interface and viceversa.

    I know the coding part but wanted to know the problem in using the above in the wrong place.

    Any could you please explain me the above with scenarios..

  • User profile image
    Dr Herbie

    Abstract classes have default implementations for one or more methods, interfaces don't have any default implementations. Simple.

    Herbie

  • User profile image
    wkempf

    @Dr Herbie: Sorry, that's not correct, nor does it explain why to use one over the other.

    public abstract class Foo
    {
       public abstract void Bar();
    }

    There's no default implementation for any method to be found in that example.

    The truth is, if we had multiple inheritance there would be no reason to use interfaces. But we don't. So, in general it's best to define an interface first. Then you might want to provide an abstract class to help with implementing the interface.

  • User profile image
    spivonious

    Think of an interface as a pure abstract class. Whether you use one or the other is a choice that you must make at design time.

    I usually use abstract classes if I have a default implementation of one or more methods. If not, I'll stick with an interface.

  • User profile image
    wkempf

    @spivonious: You can't ignore the elephant in the room. You can implement multiple interfaces, you can inherit only one class (abstract or not).

  • User profile image
    magicalclick

    Interesting question because I didn't think C# supports Abstract Classes until now. Does this feature requires certain .NET version and above?

    I did a quick Bing learning and here is a simple article.

    http://www.techotopia.com/index.php/Understanding_C_Sharp_Abstract_Classes

    I am pretty sure you cannot use virtual method in an interface, which sets apart from abstract class.

     

    Leaving WM on 5/2018 if no apps, no dedicated billboards where I drive, no Store name.
    Last modified
  • User profile image
    magicalclick

    ahhhh, now I see what's going on, you still cannot inherit multiple abstract classes, it is not C++.

    Here is a quick comparison

    http://en.csharp-online.net/Should_I_use_an_abstract_class_or_an_interface%3F

    Meaning, if you want multiple inheritance, interface only. C# is still single inheritance where abstract class cannot be instantiated.

    Pros on abstract, versioning, read the link. Cons, single inheritance obviously.

    Leaving WM on 5/2018 if no apps, no dedicated billboards where I drive, no Store name.
    Last modified
  • User profile image
    Richard.Hein

    , magicalclick wrote

    I am pretty sure you cannot use virtual method in an interface, which sets apart from abstract class.

    All methods in a interface are virtual.

  • User profile image
    wkempf

    @Richard.Hein: *sigh* No, no methods on an interface are virtual. The terms "virtual" and "abstract" apply only to classes. For that matter, @magicalclick is just as wrong when he says "if you want multiple inheritance, interface only", because you don't inherit interfaces. You implement them. Right now I may sound like a grammar *, but most of the confusion surrounding these topics comes from incorrect usage of terms such as these.

    The fact that methods/properties on an interface aren't virtual/abstract is important to note because if they were you'd be able to override them when you inherit from a class that implements the interface. You can't, unless the implementation declares the method/property to be virtual/abstract.

  • User profile image
    spivonious

    , wkempf wrote

    @spivonious: You can't ignore the elephant in the room. You can implement multiple interfaces, you can inherit only one class (abstract or not).

    True, but that's not a rule across platforms. C++ lets you do it, for example. .NET and Java don't.

  • User profile image
    Richard.Hein

    , wkempf wrote

    @Richard.Hein: *sigh* No, no methods on an interface are virtual. The terms "virtual" and "abstract" apply only to classes. For that matter, @magicalclick is just as wrong when he says "if you want multiple inheritance, interface only", because you don't inherit interfaces. You implement them. Right now I may sound like a grammar *, but most of the confusion surrounding these topics comes from incorrect usage of terms such as these.

    The fact that methods/properties on an interface aren't virtual/abstract is important to note because if they were you'd be able to override them when you inherit from a class that implements the interface. You can't, unless the implementation declares the method/property to be virtual/abstract.

    Hmm ...

    interface IFoo{    void Bar();}

    ILDASM:

    .method public hidebysig newslot abstract virtual

            instance void  Bar() cil managed

    {

    } // end of method IFoo::Bar

    Abstract and virtual.  Well, you made me doubt myself enough to check.

  • User profile image
    AndyC

    @Surendiran Bala: Dare i say that if you aren't sure, you should probably be using an Interface as it's usually the better option.

    Abstract classes are something of a more pure OOP ideal and fit better with a design that heavily leverages polymorphism, but such designs tend to be over-architected and unnecessary. By contrast Interfaces are a much looser concept that is a little less purist from an OO perspective but generally lends itself to less complex and more flexible designs.

  • User profile image
    cbae

    The main difference is that if you use an abstract class and then write generalized code against that abstract class, you're forcing all concrete instances to belong to single hierarchical lineage of class.

    If you generalize to an interface, you're writing code that does not enforce a single class hierarchy or any class hierarchy for that matter.

    Since abstract classes and interfaces aren't mutually exclusive, you can use both. Use an interface to enforce consistency of method signatures and then abstract classes to enforce a particular lineage of class hierarchy.

  • User profile image
    Dr Herbie

    , wkempf wrote

    @Dr Herbie: Sorry, that's not correct, nor does it explain why to use one over the other.

    1
    2
    3
    4
    public abstract class Foo
    {
       public abstract void Bar();
    }

    There's no default implementation for any method to be found in that example.

    But what is the purpose of code like that?  Why would you make it abstract and not an interface?

    If I saw that in live code I would change it to an interface.

     

    I get what you mean about multiple inheritance. In C++ I would have used a pure abstract class with no implementation instead of an interface because I never liked to use multiple inheritance with real implementations in the base class. I was so glad that C# didn't allow it.

    Herbie

  • User profile image
    cbae

    As I said earlier, there could be a reason why you'd use one or the other or even both. Here's a really silly example of how you'd use both an interface and an abstract class.

    class Program
    {
        private interface IVehicle
        {
            void Move();
        }
    
        private abstract class Car : IVehicle
        {
            public abstract void Move();
    
            protected void Drive(string name)
            {
                Console.WriteLine("Drive " + name);
            }
        }
    
        private class Toyota : Car
        {
            public override void Move()
            {
                Drive("Toyota");
            }
        }
    
        private class Ford : Car
        {
            public override void Move()
            {
                Drive("Ford");
            }
        }
    
        private abstract class Bicycle : IVehicle
        {
            public abstract void Move();
    
            protected void Peddle(string name)
            {
                Console.WriteLine("Peddle " + name);
            }
        }
    
        private class Cannondale : Bicycle
        {
            public override void Move()
            {
                Peddle("Cannondale");
            }
        }
    
        private class Bianchi : Bicycle
        {
            public override void Move()
            {
                Peddle("Bianchi");
            }
        }
    
        private static void MoveDownStreet(List<IVehicle> vehicles)
        {
            Console.WriteLine(String.Empty);
            Console.WriteLine("Move IVehicles down the street");
            vehicles.ForEach(v => v.Move());
        }
    
        private static void MoveDownLeftLane(List<Car> cars)
        {
            Console.WriteLine(String.Empty);
            Console.WriteLine("Move Cars down left lane");
            cars.ForEach(c => c.Move());
        }
    
        private static void MoveDownBikeLane(List<Bicycle> bikes)
        {
            Console.WriteLine(String.Empty);
            Console.WriteLine("Move Bicycles down bike lane");
            bikes.ForEach(b => b.Move());
        }
    
        static void Main(string[] args)
        {
            var allvehicles = new List<IVehicle>();
            allvehicles.Add(new Toyota());
            allvehicles.Add(new Ford());
            allvehicles.Add(new Cannondale());
            allvehicles.Add(new Bianchi());
    
            MoveDownStreet(allvehicles);
            MoveDownLeftLane(allvehicles.Where(v => v.GetType().BaseType == typeof(Car)).Cast<Car>().ToList());
            MoveDownBikeLane(allvehicles.Where(v => v.GetType().BaseType == typeof(Bicycle)).Cast<Bicycle>().ToList());
        }
    }

  • User profile image
    cbae

    Note that in my example above, the declaration of Move() as an abstract method in both the Car and Bicycle abstract classes count as an implementation as far as IVehicle is concerned. Yet, they are still not implemented as concrete methods as far as the abstract classes are concerned.

  • User profile image
    AndyC

    @cbae: That's a really hideous mix of interfaces and abstract classes though.

    From a pure OO perspective an abstract class represents an "is a" relationship wheras an interface is more of a "can behave like a" relationship.

  • User profile image
    Dr Herbie

    @AndyC:  I go with your definition of an abstract class as being closer to an 'is a' relationship.

    Whereas I tend to think of interfaces as 'shapes'.  Any instance that has that 'shape' can be used by code that is coded against the 'shape' of the interface (the I in SOLID).

    So is an abstract class is 'is a', then an interface is a 'looks like a' Tongue Out

    Herbie

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.