Why use interfaces instead of inheritance?

In the part of the course about the Strategy Pattern, the abilities are created as classes that implement an IAbility interface. I am wondering why this is preferred over having an abstract Ability class and having ability classes that inherit from it. This allows the parent classes to have common functionality and not reuse code. If two abilities are very similar and do some of the same functionality then the interface approach requires the code to be repeated in both classes, but with inheritance they can inherit from an abstract class that defines the functionality only once, allowing for it to change without having to change code in multiple places.

I am sure there’s a good answer to this, but I don’t understand the advantage to the interface method in this example. Thank you.

EDIT: this was covered in the next lecture. Hadn’t watched that one yet.

1 Like

The advantage to using an interface is that the interface could be added to any class, where once you have set something into an abstract class, you’ve cemented those properties… for example, if our Ability strategy was an abstract AbilityBase rather than an IAbility, then you would be locked into the ability being a MonoBehaviour or a ScriptableObject, depending on how you chose to implement it. With an Interface, you could have

public FireAbility : MonoBehaviour, IAction
and
public RageAbility : ScriptableObject, IAction

and both would be assignable to the ability.

In practice, however, it’s likely that you’ll be choosing one or another. For example, we use the Strategy pattern in our Shops and Abilities course from the RPG Series. In that case, our Strategies are all ScriptableObjects and do have Abstract bases. If you know you’ll only be using MonoBehaviours or ScriptableObjects, then it’s fine to use abstracts.

4 Likes

Another advantage is that you can implement multiple interfaces, but only one class

2 Likes

Ah yes, makes sense. Thank you both.

Also, with C# 8 you can have default implementations in the interface. I remember when Unity first implemented C# 8 (v2020.2), this was the one thing missing from their implementation. I am not sure if this has changed. I will have to do some research

Edit from v2021.2 Unity supports C# 9 and they do not list default interface implementations as one of the unsupported features

Just tested this. Works like a charm. Score this as a win for interfaces in the abstract vs interface column!

1 Like

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms