Travier
Travier

Reputation: 225

C# OOP - One class can be two different things (Inheritance Issue)

I'm making a console game in C#, and have encountered a problem with the OOP paradigm.

I have an Item class:

class Item
    {
        public int SellPrice;
        public string Name;
    }

And a ShopItem class, which represents Item objects that can be bought in shops:

class ShopItem : Item
    {
        public int Price;
    }

And finally, a weapon class:

class Weapon
    {
        public int Attack, Durability;
    }

Now, every Weapon object is an Item (the inheritance here was purposefully removed), but that creates a major problem.

While you can buy some weapons in shops, you can only get others by completing quests.

So, a Weapon is sometimes a ShopItem (because it could be bought in shops), and sometimes it's just an Item (which cannot be bought in shops).

Items sometimes can be bought in shops if they're ShopItem, though (becuase ShopItem inherits from Item).

So what can I do here? I obviously cannot inherit from both, and if I inherit from the Item class, than I cannot sell the Weapon object in shops (because I wouldn't be able to cast it into a ShopItem).

What do you think is the best solution for such a thing?

Upvotes: 0

Views: 173

Answers (2)

davioooh
davioooh

Reputation: 24676

You could define an interface:

interface IWeapon{}

And change your hierarchy this way:

class ShopWeapon : IWeapon, ShopItem {}
class Weapon : IWeapon, Item {}

Upvotes: 1

Rik
Rik

Reputation: 29243

You should be thinking in terms of behaviors (methods) instead of properties when designing class hierarchies, i.e. what can you do with an item?

In your example, I don't think ShopItem should inherit from Item, but rather you should define an interface IBuyable which indicates an Item can be bought.

Upvotes: 4

Related Questions