Static fields and inheritance
809141May 17 2011 — edited May 31 2011I imagine this sort of question has been asked and answered a number of times on this forum, but I can't seem to find a definitive solution to my particular problem, so here goes.
Let's say I have a class called "Animal," and that, in my program, there are two types of Animals, a Horse and a Cow, which extend the Animal class. Of course, I put dynamic fields and methods common to both in the parent class (Weight, Age, Gender, etc.). But what about static fields common to both? For instance, let's say all my cows eat hay, and all my horses eat oats (apologies to any farmers on the forum). I have a method that feeds each animal in the corral, and it shouldn't have to know what kind of feed the animal needs. I want to create an Animal, and use it as an iterator, calling Animal.Feed() for each object in the collection.
Confronted with this problem, my first thought is to create a static field in Animal called "feedType," which would be inherited by Horse and Cow. A routine loads a configuration file that specifies the type of feed for each Animal: Horse.feedType = "Oats", etc. Does this, in fact, work, or does it cause problems? Is it bad practice, as some seem to think? Is there a better way, perhaps using interfaces? Any and all input would be much appreciated.