So let’s says I have a class called Fruit, and derived from it is two classes, Apple, and Pear. So I then make two GameObjects, named Apple and Pear with the classes of those same names attached to them respectively. So I now have two instantiated classes of the Fruit class, but what code do I write in the Fruit class that will tell me whether it is has been instantiated because Pear class was instantiated, or because Apple class was instantiated? I think I’m missing a word that would be really helpful for this that would look something like “Apple class is the ______ of Fruit class.” if it was used in a sentence. Thanks.
Apple is derived from Fruit, or one can say, Apple class is the derivative of Fruit class. In English, anyway.
However, there is a slight missing bit of logic in your statement. Fruit can be instantiated itself, so there is no Pear or Apple required.
Unless, Fruit is abstract. If Fruit is an abstract class, it can’t be instantiated. Only a derivative of Fruit which resolves the abstract requirement can be instantiated.
If Fruit has no real abstract design requirement (that is, there’s nothing about abstract functions you need), then there is no real demand that Fruit be abstract. In such a case you can still implement an abstract declaration of Fruit where the only purpose is to ensure Fruit can’t be instantiated by itself.
You have to choose your preferred strategy based on your intent regarding Fruit. If you declare Fruit to be abstract, and provide a trivial abstract function which Apple and Pear must supply, there can never be an Fruit instantiation unless it is either an Apple or Pear (or whatever derivative may be declared). An abstract function that returns a type from an enumeration would be appropriate (you can get a number from a Fruit perspective that says it’s an Apple, Pear or whatever.
If you allow Fruit to be instantiated, then the test situation you indicate will be required to know if any Fruit happens to be an Apple or a Pear. You then attempt a cast and see if it fails.
Fruit f = new Apple();
Pear p = f as Pear;
Apple a = f as Apple;
In this example, p would be null because the cast fails. A would be an Apple, not null, because the cast worked.
You can also use the “is” keyword to ask, then get a bool, assuming f declared as above:
bool isApple = f is Apple;
bool isPear = f is Pear;
Choose this if you don’t want a reference, but just want to ask (get a bool true/false) if the type can be downcast. In this case, since f, of type Fruit (and therefore not recognizable yet), was instantiated as an Apple, isApple will be true, but isPear will be false.