Hello,
Great overview of virtual methods and subclasses… I’m in the ‘new at this’ camp, so I am curious when you would use an Interface and when you would use Subclasses with virtual methods? They seem to have slightly similar functionality.
From my understanding I would not call an interface directly- rather, I would implement it from a class.
As opposed to a class with a virtual method would be useful if there’s a chance I’ll implement the parent class or the subclass??
Thank you for any clarification you all can lend!
Interfaces and Subclassing are similar in some ways, but each have very different approaches… Interfaces define common functionality, Subclassing defines common identity. Think “is” (Subclassing) vs “Can do” (Interfaces).
An interface allows you to take many disparate objects with nothing else in common and treat them as the same type of object (subject to the restrictions of the interface). So you could have something like this:
public interface IHaveADescription
{
string GetDescription();
}
and anything that implements IHaveADescription could be gathered to get the descriptions. The limitation of this is that all we can do. If it isn’t in the interface, we can’t see anything else about the object unless we try casting the object into other things.
When things have a significant number of things in common, it’s better to have a common parent class with the core functionality built in. A great example is found in our Inventory… all inventory items have a Description, a stackable property, a pickup associated with the item, etc. By having all inventory items descend from InventoryItem, they automatically have all these properties.
Here’s a great answer on Stack Overflow that describes this better than I can.
This topic was automatically closed after 23 hours. New replies are no longer allowed.