Download

When do I use an interface as opposed to using class inheritance?

I was curious, being somewhat new to OOP, as to when it is more appropriate to use blueprint interfaces as opposed to class inheritance for duplicated functionality?

I understand the interfaces are great for applying function A on car, frog and rock classes. But if these classes had a common parent, wouldn’t that it be better to implement function A in the parent than using an interface?

Is inheritance really only appropriate when you need function A implemented on extremely different classes that would never allow for a common parent?

Thanks!

If these classes had a common parent…thats the point. You could put everything in a base class “Object” but that would make the base class bigger and bigger and most of the time you might have methods that do not realy apply to the base class or your inheritance tree is huge. The interface is a elegant way around it. Its a contract that if an object implements an interface it has the methods defined in the interface. Even Objects that don’t share the same base classes can have the same methods if they implement the same interface.

But sure, you can do the same with inheritance and it is up to you to choose.

So really i should be focusing on keeping classes specific as much as possible.

I’ve also noticed that interfaces are used to communicate between blueprints - is this the ideal method for this purpose? Or is it better to simply have an instance of the class object in a blueprint with the specific variables made public?

Thanks again for your time, big clarification.

Interfaces are when you want very different objecst that are in different hierarchy to communicate. A good example is my IUsable interface. You could want a actor in the map to be usable, or a player, or a door, but a Usable class is not good, becouse you also need to inherit from others. So the IUsable interface allows very different objects that are very different classes to share the Use function in common so they can communicate with the player.

Thanks again, that’s a great example.