Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an interface and an abstract class with just virtual abstract methods the same thing?

If I have a project that contains similar classes and some may use the same implementation, but in most cases they implement their own way of handling the methods defined in an interface or abstract class. I am trying to figure out if an interface/abstract class is better or not. I don't get the point of an interface if you can just use an abstract class with virtual abstract methods.

Here is an interface:

public interface IAthlete
{
    void Run();
}

Here is an abstract class:

public abstract class Athlete
{
    public abstract void Run();
}

Here is an implementation of the interface:

public class Sprinter : IAthlete
{
    public void Run()
    {
        Console.WriteLine("Running Fast....");
    }
}

Here is an extension of the abstract class:

public class MarathonRunner : Athlete
{
    public override void Run()
    {
         Console.Write("Jogging....");
    }
 }

Now if I decide to add a method called Stop to either the interface or abstract method, Sprinter and MarathonRunner both break and because I can provide some default implementation to abstract, it seems like a better choice. Am I missing something?

like image 242
Xaisoft Avatar asked Aug 12 '11 14:08

Xaisoft


1 Answers

There are 2 main differences between Interfaces and abstract super-classes:

Abstract Classes

  • code reuse is possible by using an abstract super-class
  • you can only inherit one super-class

Interfaces

  • every method has to be implemented in each sub-class
  • a class can inherit more than 1 interface (multiple inheritance)
like image 98
rivalitaet Avatar answered Oct 04 '22 12:10

rivalitaet