Interfaces are used for broader systems, where the classes that implement it are not necessarily related. Whereas, usually,classes extending an abstract class would be somewhat related, such as a list in your case. Also interfaces only guarantee behavior, and the methods will need to be implemented in the classes implementing them. Abstract classes can define methods that will be used in classes extending them to promote code reuse. Answer from Laghacksyt on reddit.com
🌐
Reddit
reddit.com β€Ί r/csharp β€Ί abstract class vs. interface ?
r/csharp on Reddit: Abstract class vs. Interface ?
December 24, 2021 -

What is the difference between the two?

I understand that a derived class can only inherit from one base (abstract) class, but can inherit from multiple interfaces. However, I also believe that inheriting from multiple interfaces should be avoided, as it typically means the class is trying to do too much.

So what is the difference? When would you use one over the other?

Top answer
1 of 17
57
You don't inherit an interface, you implement it. An interface says something about what a class does (which is why interface names are typically verbs), whereas an abstract class says what a class is. If you want to define what a class does, you use an interface Implementing multiple interfaces is common. In fact, the I in SOLID stands for Interface Segregation. So implementing multiple interfaces is even considered good practice
2 of 17
12
An interface defines a minimum set of methods and/or properties that a class must implement. An abstract class provides a default implementation to its inheritors. I like how you specified "should be avoided" as it pertains to multiple interfaces. As with most everything the true answer is that it depends. Having multiple interfaces can be perfectly valid. For example, List which is ICollection, IList, IEnumerable, IList, et al. It has a bunch of interfaces, but fundamentally List does one thing. Contrast that with MySuperClass which is IMyDocumentReader, IMyDocumentWriter, IMyTranslator, et al. That class clearly does too much. People shy from abstract classes, because they tend to start to do too much that can potentially drive a hierarchy of classes that could've been better implemented with composition. For example, what if our previous example, MySuperClass was a director/mediator that needed to coordinate the reader, writer, and translation operations. In that case you could "have" a reader, writer, and translator in the director/mediator and all it did was called out to them. All these things are what I love about software design. There is no one pat answer and you should dismiss anyone that says anything in an absolute. Personally, I would recommend that you almost always start with interfaces when inherited behavior is needed and then if your set of concrete classes have a common, partial implementation than include a base class that implements the interface.
🌐
Reddit
reddit.com β€Ί r/csharp β€Ί whats the difference between interface and abstract class? are they not use the same way?
r/csharp on Reddit: Whats the difference between Interface and Abstract class? Are they not use the same way?
October 29, 2020 - Traditionally, interfaces don't allow any implementation, but I think one of the more recent versions of C# have changed that. I still think it's bad practice. The facade pattern is a great use case to study.
🌐
Reddit
reddit.com β€Ί r/learnjava β€Ί abstract class vs interface
r/learnjava on Reddit: Abstract class vs Interface
February 18, 2024 -

Hey everyone, thanks for dropping by, recently learnt about abstract class and interface at school.

In work experience, when would you use abstract class and interfaces vice versa, what’s the benefit over the other?

Interface, for me it is wonderful because it is a contract and we need to implement all the method, makes the class implements the interface much easier to understand.

What’s your view and experience on the two? Thank you for your time

Top answer
1 of 5
13
As a rule of thumb, I think of interfaces as "type definitions" and abstract classes as "partial implementation definitions." Technically, an interface and type definition could mean two different things, especially in Java but also depending on the language you use, but I find it useful to think of it this way because it entails that the interface specifies a contract but doesn't specify anything about how the thing is implemented. For that reason, it's more lightweight and easier to pass around and use. Abstract classes could technically be used "as" interfaces, but it generally carries a bit more baggage, as it entails that there is some kind of implementation going on that the user cares about. Usually, an abstract class defines some core functionality but leaves the rest to the subclass, so anyone looking to use an interface vs abstract class (if both are available) would only choose the abstract class as a type if they want something specifically from that class's implementation. Overall, interfaces are lightweight and simple to use, since they carry less baggage and can be substituted more easily, whereas abstract classes provide useful core implementations but restrict the user from using other classes that conform to that interface but don't inherit from that abstract class.
2 of 5
8
Abstract classes are great for defining a base entity that other classes should inherit from. Think like Executive extends Employee or CalculationSummaryCache extends SummaryCache Interfaces define behavior and not necessarily a parent type. You can have many unrelated classes implement a particular interface, whereas unrelated classes inheriting from an abstract class would be inappropriate. Think of an interface that requires its implementers produceCsvReport(). The implementing classes need not be related to each other at all, they just need to uphold the contract.
🌐
Reddit
reddit.com β€Ί r/csharp β€Ί interface vs abstract vs base
r/csharp on Reddit: Interface vs Abstract vs Base
March 11, 2020 -

I have the question of what is the use case for each of the above. I understand how inheritance works and everything. No problems there.
What I don't get is where to use each. I've almost always just solved my problems with base classes.

Say I have this :

class a {
  virtual void stuff() {}
}
class aa : a {
  override void stuff() {}
}

Why would I not want to go this route? If I don't need to override the method I can simply leave it as is and there should still be a working stuff method.
Where do I put an interface or abstract class? Are all three methods do be used in tandem?

Again, I don't struggle with how they work, I'm just asking why use them. Say I was building a big app with lots of inheritance. How would I set up my architecture in the "best" way possible?

Top answer
1 of 5
22
The Stream class is a good example for all of that in action. Abstract classes: You use them when you want to prevent instantiation of the base class. Instantiating just a "Stream" doesn't make sense. It always needs to be something specific like a MemoryStream or FileStream. Interfaces: With inheritance you can just derive from a single base class, but you can add as many interfaces as you like. The Stream class for example derives from MarshalByRefObject, but it also needs to be disposable, which MarshalByRefObject isn't. Because IDisposable is an interface it can easily be added to the Stream class. And in .NET Core it even implements IAsyncDisposable as an added bonus.
2 of 5
20
C# 8 made this a little less "clean". Keep in mind expert devs still argue about what is "right" here. u/NekuSoul 's answer is good, and so are u/RiPont 's points. If you really want to amp up your learning, I recommend books like Head-First Design Patterns and Working Effectively with Legacy Code. Some people hate the SOLID style of development, but I found it to be a lifesaver. Anyway, in order of flexibility they go: Interface, Abstract Base Class (ABC), Base Class. They are all tools of abstraction. That means we use them when we want our program/algorithm to think about "Fruit" instead of "Apples", or "round things" instead of "apples and oranges". If you've ever played Spelunky or another roguelike, part of how they have amazing complexity is they use abstraction heavily in code, so a boulder is "a round, heavy thing" and behaves like "a spike ball" or "a steel ball" etc. I'm going to throw in one form of abstraction you didn't mention, but is just as important: Composition. It's at least as flexible as interfaces, but I will discuss it last because it just makes the most sense that way. Interfaces before C# 8 say what a type does, but not necessarily how. So you could make an interface with a Sort() method that sorts an array, then several different classes that implement different sort algorithms. The main difference between interfaces and the other two is any class can implement any number of interfaces, but only one base class. That makes interfaces good when you want your types to have very flexible behavior. For example, you could use interfaces to describe "a duck" as: "a thing with feathers and wings that can swim and quack". Some people don't like that interfaces don't define a default behavior, C# 8 gave that to them. We use them because sometimes we're dealing with a situation like, "I want to have a lot of different Bird types, but that must include Penguin (a bird that can swim and can't fly) as well as Ostrich (a bird that can't fly) and I want to be able to ask for "all birds that can fly" without thinking very hard about it. Or, in some practices, we use them for almost every type, but there are short books I can recommend to describe those circumstances. Abstract Base Classes are quite a bit less flexible, mostly because types can only derive from ONE class. Like an interface, they are able to (in fact, they are required to) define "abstract" methods that have no behavior other than the parameters they take and the return value. BUT, they can also define methods that have fixed behavior derived types cannot override! The nice part about an ABC is you can provide an implementation for a lot of how the type behaves, then leave some tiny details up to whoever derives from it. So you can make "a bird that can fly", but leave how it flies up to the implementation. Or, you can make "an array that can be sorted", but leave the details of the sorting algorithm up to the implementor. See how I keep referring to types as "a thing that "? That's how abstraction works. Base Classes provide the least flexibility, but it is still greater than zero. These are just plain old classes with behavior. If you derive from them, you can ONLY change the behavior if they marked one or more methods virtual. That's an interesting case. It's like you said, "Here is a duck, I've described how it flies, but there might be special ducks that fly a different way." Or, "Here is an array, I've implemented the Bubble Sort algorithm, but you can create a version that uses QuickSort if you want." The big difference between a Base Class and an Abstract Base Class is you can use a BC directly, whereas an ABC requires you to derive a type so you can define the abstract methods. That is to say, an ABC is more like an interface than a base class. The main reason there's a fight over these three things is philosophical. Some developers don't like that you can only derive from one ABC or BC. I chose Birds as an example for a reason. ABCs and BCs are not a good way to handle the situtation where you want to say both, "an ostrich is a bird" and "an ostrich cannot fly". Or, at least, you can't say, "A bird is a thing that flies" if you also want to say "an ostrich is a bird". Interfaces let you more elegantly say, "A bird is a thing with these behaviors, and while most birds can fly it is not the core behavior of a bird." So how does code reuse happen if interfaces/ABCs can't define their behavior? Composition. If I say, "a thing that flies" means it implements the IFly interface: public interface IFly { void Fly(); } I can write a very generic class: // Imagine the rest, it's only important that this exists public class BirdFlyBehavior : IFly Then I can implement "birds that fly" in terms of a class that looks like: public class FlyingBird: Bird, IFly { private IFly _flyingBehavior; public FlyingBird(IFly flyingBehavior) { _flyingBehavior = flyingBehavior; } public void Fly() { _flyingBehavior.Fly(); } } So this is "a Bird that can Fly", but since I "have a thing that defines how I fly", we say it's a type composed from other types. And when it has to fly, it delegates to another type. This is incredibly flexible! I can have 10 different FlyingBird derived types using any mix of up to 10 different Fly() implementations, but I they can also share flying behaviors without writing a lot of code! public class Albatross : FlyingBird { public Albatross() : base(new GlidingFlyBehavior()) { } } public class Eagle : FlyingBird { public Eagle() : base(new GlidingFlyBehavior()) { } } public class Harrier : FlyingBird { public Harrier() : base(new AcrobaticFlyBehavior()) { } } Look at that! I implemented 3 different types of bird, 2 that share the same Fly() method, and I barely wrote a line of code! You can also use composition with base classes, but let's start another topic. The above used interfaces exclusively, but suppose we had this class: public abstract class FlyingBird : Bird { public abstract void Fly(); } This is actually the same thing as the interface-based approach! Imagine if I wrote this: public class FlyingBehaviorBird : FlyingBird { private IFly _flyingBehavior; public FlyingBehaviorBird(IFly flyingBehavior) { _flyingBehavior = flyingBehavior; } public overrides void Fly() { _flyingBehavior.Fly(); } } See? Now I'm using BOTH an abstract base class and an interface. Maybe some of my birds use commonly-shared flying behaviors, but a few have really special ways to fly so I don't want to make an interface implementation. But a base class is a bit too inflexible for this lesson. This would be harder to justify: // WRONG! public class FlyingBird : Bird { private IFly _flyingBehavior; public FlyingBehaviorBird(IFly flyingBehavior) { _flyingBehavior = flyingBehavior; } public virtual void Fly() { _flyingBehavior.Fly(); } } At this point it's just confusing. If I have to provide the behavior, why can a derived type override the method? That might allow them to NOT use the behavior they provided, but then it's superfluous. This tends to indicate someone didn't think very hard about their requirements. Devs fight hard over which is "right", mostly because some people haven't matured enough to lose an ego and realize there are a lot of "good" ways to write a program. Part of the fight is over whether it matters. Some people argue that, in their program, they want "a bird" to mean "a thing that flies", and they're just not going to consider Penguins or Ostriches "a bird" if they're supported at all. This is fine. What's important is they have identified that "flying" is what's important to their program, and if a thing "doesn't fly" then it isn't a Bird. Sometimes this is OK. If you're writing a program about managing Apple orchards, it's a waste of time to write a way to also support Oranges. Unless, after a few years, your company decides to expand. Then you're in trouble, if you decided part of "an apple" is "a thing with a stem", etc. In short: Many people favor composition and interfaces because it's proven extremely flexible. Many people favor inheritance because they know for a fact they don't need that flexibility. Both of these groups of people are right, because they analyzed their problem, chose a solution, and shipped their software. But if either has a hard time maintaining the program later, they're wrong if they don't repeat that analysis. The best way to learn is to write programs for several years, try both techniques, and be honest with yourself about when it goes wrong. The only people who are wrong are the people who say you should NEVER or ALWAYS use one of these approaches: these are people too shortsighted to realize not all programs are like theirs so not everyone will be best served by their experience.
🌐
Reddit
reddit.com β€Ί r/learnprogramming β€Ί java interface vs. abstract class - when to use which one?
r/learnprogramming on Reddit: Java Interface vs. Abstract Class - When to use which one?
May 21, 2015 -

I've been programming for eight years now and I have a few languages under my belt, but I've just realized that I don't really know when to use which of these tools over the other.

I have the general idea of "Abstract classes can be partial implementation, vs Interfaces you must define each method of an implemented Interface".

But for some examples, say you have a few classes for a simple game:

Entity which will have subclasses/ concrete implementations of "Player" and "Enemy".

What would be the best way to go about this?

Entity = Interface, Player & Enemy = Abstract/ normal classes implementing Entity?

Entity = Abstract Class, Player & Enemy = standard classes extending the Abstract Entity's functionality?

Perhaps this question can't be answered without further details on the Entity/ Player & Enemy classes, in terms of how they would be interacting/ if there's any default implementation for the Entity class, but if any sort of answer can be given for clarity, all would be appreciated.

Also, same thing would go for an example like:

Item = Interface or Abstract Class?

Consumable = Standard class implementing Item, or concrete extension of Abstract Item?

Same for Equipment/Equipable & Throwable? (for Items).

Again, I feel like this may just be something that requires messing around with, but any and all input is helpful!

EDIT: Formatting.

Find elsewhere
🌐
Reddit
reddit.com β€Ί r/learnprogramming β€Ί [java] why would you use an abstract class as instead of an interface?
r/learnprogramming on Reddit: [Java] Why would you use an abstract class as instead of an interface?
February 8, 2014 -

The deal with abstract classes is that they are abstract, you can define abstract methods and also concrete methods. Them being classes means that when creating new classes you are limited to extending only one per class.

Interfaces on the other hand define abstract methods and also concrete methods through what I now learned is another use of the default keyword (the one I knew was switch cases). Interfaces can also be functional interfaces which means support for lambdas. You can implement more than one interface in a class.

Now that we know that both abstract classes and interfaces provide both support for concrete and abstract methods, and that you can "subclass" more interfaces in one class as opposed to "subclassing" abstract classes, as well as lambdas support for interfaces, why would there be a use for abstract classes? It seems interfaces can do all that abstract classes can do but better.

Top answer
1 of 5
38

Basically you want, if possible, to use interfaces wherever possible. The only difference between an interface and an abstract class, aside from classes only being able to extend one class, is that abstract classes can contain state. If you don't need to contain state it's better to use interfaces since a class can implement any number of interfaces.

So to answer your question:

It seems interfaces can do all that abstract classes can do but better.

No. Abstract classes can contain state, interfaces can't.

An example for using interfaces, abstract classes and concrete classes:

public interface UserDb {
    void storeUser(User user);
    default void storeUsers(User... users) {
        for(User u : users) {
            storeUser(u);
        }
    }
}

public abtract class AbstractUserDb implements UserDb {
    protected List<User> users = new ArrayList<>();

    @Override
    public void storeUser(User u) {
        users.add(u);
    }
}

public class JsonUserDb extends AbstractUserDb {
    @Override
    public void storeUser(User u) {
        super.storeUser(u);
        new ObjectMapper().writeValue(users, "users.json");
    }
}
2 of 5
14

Abstract classes can provide implementation of methods as well as just declarations, so they can provide common or base implementations for methods that may be used by many subclasses. Take a look at java.util.AbstractList, for example, which provides some base functionality to make it easier to implement the java.util.List interface. If you want to implement List, you don't have to actually implement all of the methods declared by that interface yourselfβ€”you can just extend AbstractList and implement the get() method, and the default implementations of all the other methods provided by AbstractList will work out of the box, using your get() method, to give you a minimal implementation of List.

🌐
Reddit
reddit.com β€Ί r/learnjava β€Ί when does it make sense to use an abstract class versus an interface?
r/learnjava on Reddit: When does it make sense to use an abstract class versus an interface?
June 26, 2022 -

In Java, interfaces are almost preferred for their flexibility. What cases would you use an abstract class? I’m having trouble thinking of good heuristic to choose this. Is it best to think of it as a partial implementation?

I can think of the Abstract classes in the Collections API like AbstractList, which are like a skeletal implementation. Also HttpServlet and Verticle from vertx. In these cases it makes sense because you have only one implementation that can be extended.

🌐
Reddit
reddit.com β€Ί r/java β€Ί explain like i'm five : inteface vs classes / abstract classes
r/java on Reddit: Explain Like I'm Five : Inteface vs Classes / Abstract Classes
August 2, 2010 -

I'm working on a project in Computer Science and interfaces are really tripping me up.

EDIT : I didn't get a chance to check during class because I was rushing to get my work done, but thanks guys!

Top answer
1 of 5
12

An interface is a promise that the class implementing the interface is able to do something, without specifying exactly how the class should do it.

Different classes implementing the same interface may do that something in different ways, but they promise to do it in some way specific to that class.

For example, java.util.ArrayList implements List, and thus promises that ArrayList is an ordered list of elements that implements get(int index) and add(int index, Object o) and so forth.

So if you don't care what kind of list you have, just that you want an ordered list of elements, you use the interface List.

List in turn is a Collection, which is what you use if you have a collection of elements, and don't care how they're stored. All you know is that you have a collection that you can .add(Object) and find out how many there are, through .size(), and so on.

Collection in turn is an Iterable, which means you have a stream of elements, and you don't know or care how many or how they're stored, just that you can get them in some order specific to the implementing class, through .iterator().

And then there is java.io.Closeable. Any object implementing Closeable promises that it can be closed. You don't have to know anything else about the object, but if you want to close it, you can.

It can be a network stream, it can be an open file, it can be a database connection. It doesn't matter. If it implements Closeable, it promises that it can be closed, without you having to care how it's done.

Interfaces free you from having to know or specify exactly how something is to be done, when you shouldn't need to know or specify it.

2 of 5
8

http://docs.oracle.com/javase/tutorial/java/concepts/interface.html

As always, GO TO THE OFFICIAL TUTORIALS FIRST, then ask questions.

🌐
Reddit
reddit.com β€Ί r/learnjava β€Ί interface and abstract class
r/learnjava on Reddit: Interface and Abstract Class
May 31, 2022 -

Hi everyone,

I'm following the 10th part of mooc.fi course and i'm starting to get confused about Interfaces and abstract classes

I don't see the point of using them. If a class implements an interface, and his methods, why should i use it if i have to rewrite those methods into the class that implements it?

abstract classes confuse me more, because i can't imagine examples of when i can use them

In this course i've always thought of a way to implement stuff, but i can't find any use for these two last parts

Now that i'm doing the Comparable interfaces, it's even more confusing, because for what i've in my mind, i could just use the method "compareTo" without implementing any interface

Sorry if this looks dumb for you, but i'm just a beginner

Top answer
1 of 5
14
I don't see the point of using them. If a class implements an interface, and his methods, why should i use it if i have to rewrite those methods into the class that implements it? It might not make sense for a small application where there's only one implementation of each class, but in larger systems you might have multiple types of the same class that has different implementations. For example, maybe your system generates a file and it can generate that file in different formats, like XML, JSON, CSV, etc. Then you can use the same interface with a createFile method, but each implementation of that interface can generate a different type of file. If you look online you can find plenty of examples of why interfaces are helpful. abstract classes confuse me more, because i can't imagine examples of when i can use them https://www.baeldung.com/java-interface-vs-abstract-class#when-to-use-an-abstract-class Now that i'm doing the Comparable interfaces, it's even more confusing, because for what i've in my mind, i could just use the method "compareTo" without implementing any interface You could, but then you wouldn't be able to use it in methods that expect an Comparable. Sorry if this looks dumb for you, but i'm just a beginner It doesn't look dumb. It is however important to consider that codebases for production systems are complex and large. Things that might seem like a waste in smaller systems might be really useful in larger systems.
2 of 5
4
Interfaces form a guarantee that a certain method is available in the implementing class. Read Classes versus Interfaces from the r/learnprogramming wiki. Gives a good analogy and explanation.
🌐
Reddit
reddit.com β€Ί r/cpp_questions β€Ί abstract vs interface
r/cpp_questions on Reddit: Abstract vs Interface
June 4, 2024 -

I'm designing a window class for my renderer. I want to write it's public methods in a parent class, and then write the logic in children classes (one for sdl, one for glfw, etc). But I'm unsure about the differences between an "interface" class and an abstract class. I want to be able to write its methods, but I also want to be able to store a variable of type "Window" (which is actually a child class) use it normally. What do you guys think is the right tool for the job? I appreciate it

Edit: Thanks for the replies everyone. Honestly I just needed this post so I could write out my thoughts. Once I realized the problem, some YouTube videos and your responses really helped

🌐
Reddit
reddit.com β€Ί r/learnjava β€Ί confused with the difference between an abstract class and an interface
Confused with the difference between an abstract class and an interface : r/learnjava
March 28, 2016 - Since you can implement multiple ... all differents Lists implement the List interface. If you need to share both logic and state between classes you can use an abstract class, but only if there is a "is a" relationship....
🌐
Reddit
reddit.com β€Ί r/unity2d β€Ί is there a reason to use an abstract class instead of an interface?
r/Unity2D on Reddit: Is there a reason to use an abstract class instead of an interface?
January 22, 2021 -

It seems like interfaces are much more flexible. From what i see, an abstract class is works like a set of actions that can be triggered by different scripts? While an interface is more like a way you can make multiple things react to a certain input, and have them all react differently to it, right?

What is the purpose of each of these?

Top answer
1 of 5
4
Both can do similar things - abstract classes being able to do everything interfaces do. Which you use depends more on development principles than the end result. Interfaces are just an agreement to implement certain things. In unity, right now, that's functions. If you implement an interface, then you have to implement the functions included in the interface. However, each implementation of the interface and its functions has separate behavior defined. Let's imagine that you are doing a building based game and you want to go through a List<> of all your buildings (called IBuilding, implementing ProgressBuilding()) to make them progress. Some buildings are affected by global technologies, some buildings build faster, some buildings have special rules... and so ProgressBuilding() needs to be different for each building. You make a separate script, which implements IBuilding and ProgressBuilding(), and attach it to every single building you make. Adding them to the List<> means you can go through your List<> and .ProgressBuilding(). It works! But that's... not really simple, is it? Creating BuildingA, BuildingB, BuildingC... a separate script for every building is cumbersome when an abstract class called "Building", with all the data you need, can implement ProgressBuilding() and only override it in really special cases. In the case where you are sharing behavior, abstract classes would almost always be better. Interfaces are also prone to breaking a lot of things at once - imagine that you added .DecayBuildings() to the interface. Now every single script that implements it would be broken. You could just add DecayBuildings() to the abstract class - and it would be automatically inherited! A simple way to look at it is that interfaces define separate behavior, while abstract classes define shared behavior that can be overridden to define separate behavior. However, since abstract classes already define behavior, it also has the ability to have data/etc. In practice, the up/down side is dependent on how you are going to implement and extend behavior. Both have different types of hell that you can enter into. Adding to an interface late is an experience you only have once in your life before you are a lot more careful about where you use interfaces. Likewise, having multiple levels of inheritance on a gameobject and trying to figure out unwanted behavior can be a terrible debugging experience. Minor hells, like having 5 different interfaces because you didn't want to extend properly, also happen.
2 of 5
2
Simplicity? Look at monobehaviours. Lots of work behind the scenes going on. Also I don't think unity supporting .net versions which allow default code in interfaces is coming too soon.
🌐
Reddit
reddit.com β€Ί r/learnjava β€Ί what's the difference between an interface and an abstract class?
What's the difference between an interface and an abstract class? : r/learnjava
November 19, 2021 - Interfaces define types and specify behavior that classes should conform to. These classes don't have to be related to each other. Abstract classes define a parent type, that can be used to generate children. Usually there is some kind of abstract relation here.
🌐
Reddit
reddit.com β€Ί r/csharp β€Ί why would you use an abstract class instead of an interface in this example code?
r/csharp on Reddit: Why would you use an abstract class instead of an interface in this example code?
May 15, 2016 -

I'm reading up on some design patterns and I found the strategy pattern here: http://www.dofactory.com/net/strategy-design-pattern

In the example code an abstract class is being used and as far as I can tell an interface would be a better option. I think this because an abstract class allows you to have "common" code that anything inheriting it can use, but in this case there is none of this and it's literally just a virtual method declaration that has no code in it.

So why not use an interface, if you don't need to share any code or override a method?

 /// <summary>
  /// The 'Strategy' abstract class
  /// </summary>
  abstract class SortStrategy
  {
       public abstract void Sort(List<string> list);
  }

  /// <summary>
  /// A 'ConcreteStrategy' class
  /// </summary>
  class QuickSort : SortStrategy
  {
  public override void Sort(List<string> list)
  {
    list.Sort(); // Default is Quicksort
    Console.WriteLine("QuickSorted list ");
  }
}

/// <summary>
/// A 'ConcreteStrategy' class
/// </summary>
class ShellSort : SortStrategy
{
  public override void Sort(List<string> list)
  {
    //list.ShellSort(); not-implemented
    Console.WriteLine("ShellSorted list ");
  }
}

I'm still learning, so I might be missing something obvious. What does r/csharp think to this, why would you prefer an abstract over an interface in this scenario?

This is how I'd do it using interfaces:

public interface ISortStrategy
{
	void Sort(IList<string> list);
}

class QuickSort : ISortStrategy
{
	public void Sort(IList<string> list)
	{
		Console.WriteLine("QuickSorted list ");
	}
}

class ShellSort : ISortStrategy
{
	public void Sort(IList<string> list)
	{
		Console.WriteLine("ShellSorted list ");
	}
}
🌐
Reddit
reddit.com β€Ί r/php β€Ί any reason to use an interface over an abstract class?
r/PHP on Reddit: Any reason to use an interface over an abstract class?
August 31, 2011 -

Please explain to me why you would use an interface over an abstract class. Object interfaces is limited to public functions and it seems redundant when you can use abstract classes.

interface base {
    function foo(myclass $bar);
    protected bad_function();  //php coughs up error because it cannot do this!!!!
}

Can be replaced by:

abstract class base {
    abstract function foo(myclass $bar);
    abstract protected function bad_function();    //works here....
}

class something extends base {
    function foo(myclass $bar) {
        //do something with $bar
    }

    protected function bad_function() {
        echo 'i am here';
    }
}

So... why would you ever need to use an interface when an abstract class covers all functionalities of interfaces and some? The only case I see for using interfaces is if you need to extend a class while implementing an interface.

Top answer
1 of 3
7
Multiple interfaces can be used on a single class, but you can only extend a class once Abstract classes can be more than just function definitions - it's a regular class, you just can't use it without extending it. Abstract classes are good when you have a base object that has children which will need to implement their own versions of some functions. The parent (abstract) can define all of the shared functions, and the children inherit all of those automatically. An interface requires you to code every one of those functions (or inherit them from another class).
2 of 3
5
The two features have completely divergent use-cases, once you think about it. Interfaces establish a contract - If class Foo implements interface IBar, then all that's happening is that client code knows for sure that Foo implements whatever IBar says it has to. The interface provides zero implementation. Abstract classes provide implementation, enabling polymorphism if Foo extends an abstract class Bar, Foo inherits all of Bar's functionality. Baz can extend Bar too, and then Foo and Baz will share some common implementation details (those defined by Bar). As you note, PHP doesn't have multiple inheritance. If you go around using abstract classes in place of interfaces, you're likely to run into trouble when you later decide you need to refactor your code and actually need an abstract base class. One way to think about it, in order to keep things straight: Inheriting from an abstract class means Foo is a variety of Bar Foo implementing Bar means Foo acts like a Bar