Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I solve the issue of inheriting 2 abstract classes in my game?

My problem lies in inheriting the playable character's attributes. I have an abstract class named Being that states that all inheriting classes need to contain attributes like Strength, Dexterity, etc. The player needs to choose a race, e.g. Orc that raises the Strength from 0 to 10. Then the player needs to choose a class, such as brute, that adds 7 more points to the Hero's Strength. As far as I see it, I would be stuck with my Hero class inheriting 2 abstract classes? This is an extract of my Orc class:

public abstract class Orc:Being
{
     private int _strength = 10;



     //Another question, is it okay to declare an abstract property in my base abstract
     //class to force the inheriting class Orc to override the property? I wanted to 
     //find a way to force subclasses to have strength attributes

     public override int Strength
     {
            get {return _strength;}
            set {_strength = value;}
     }
}
like image 378
Frapie Avatar asked Dec 21 '22 10:12

Frapie


2 Answers

You can use Composition as a solution for multiple inheritance:

This answer here explains it best: https://stackoverflow.com/a/178368/340128

like image 90
Variant Avatar answered Dec 23 '22 00:12

Variant


If your abstract class has only abstract properties, you can just make it an interface instead. This forces implementing classes to provide an implementation, and you can implement as many interfaces as you would like.

Otherwise, I would take a look at the decorator pattern, or the strategy pattern. Both use composition as an alternative to inheritance.

like image 37
jonnystoten Avatar answered Dec 23 '22 00:12

jonnystoten