Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialFredrik Rönnehag
2,342 PointsInterface and Abstract Classes
Great course! I'm working on a RPG in Console. I had already started using interface but abstract class was new to me. I'm using it for my Items which will be dropped from monsters you defeat.
If I understood this correctly you can create the interface IItem which will contain all public stats that an item needs to have like stats, durability, sell price. Can you then have several abstract classes, like Armor, Sword, Axe, Shield to mold these specific items? And then use those abstract classes to create new items?
This makes the inventory a lot easier to work with, since you can make the "backpack" an array of IItems.
Just checking if I understood the course correctly, otherwise I'll recap :)
1 Answer
Steven Parker
231,198 PointsC# supports single inheritance, which means a class can only inherit from a single class. However, a class can implement multiple interfaces, and an interface can be shared by multiple classes.
As long as your abstract classes all conform to these rules, it sounds like your understanding is correct.
Fredrik Rönnehag
2,342 PointsFredrik Rönnehag
2,342 PointsWhat I mean is having an abstract class that inheritates from an interface, then the other classes inheritate from the abstract class.
Steven Parker
231,198 PointsSteven Parker
231,198 PointsIf you meant to say "an abstract class that inherits from an interface", that would also be correct.
Fredrik Rönnehag
2,342 PointsFredrik Rönnehag
2,342 PointsYes, thats what I meant. It it okay to do it that way? Interface IItem. Then several abstract classes like Weapon, Armor, Shield that inheritate from the interface. Then you make classes like Sword, Axe, LeatherArmor that inheritate from the abstract classes?
Steven Parker
231,198 PointsSteven Parker
231,198 PointsYou would not inherit from an instance. But you can inherit from an interface (or several of them).
Fredrik Rönnehag
2,342 PointsFredrik Rönnehag
2,342 PointsTypo again, im on my phone. Meant interface.
An interface IItem Then abstract classes Armor, Weapon, Shield that inheritate from IItem. Then classes Leather, Sword, Axe etc. That inheritate from the abstract classes.
Steven Parker
231,198 PointsSteven Parker
231,198 PointsThat sounds like a logical structure.