If its a common property to all child classes, put it in a parent class, otherwise declare it in the child class which will use it. It keeps the code clean and avoids unneccessary inheritance of parent properties which the child class will never need. You need to make a design decision and should carefully think what will all the child Items which extend the parent Item class will need, and what is specific to each type of item.
Joined: Feb 25, 2005
So, if only 2 of the item subclasses use the attribute a, it would still be okay to put it in the parent item class. This attribute would be unused in the third class.
Originally posted by Kimber Frye: So, if only 2 of the item subclasses use the attribute a, it would still be okay to put it in the parent item class. This attribute would be unused in the third class.
Usually when something lie this happens, the code is telling you that your inheritance relationships aren't quite right. You might consider introducing an "AItem" which extends Item, and is in turn extended by xitem and yitem. AItem would have an "a" attribute. zitem would extend Item directly, and zitem would have the "b" attribute. Now no classes have "extra" attributes.
An alternative is to make Item an interface rather than an abstract class, and have xitem, yitem, and zitem all implement that interface, and include only the attributes they need. You could still use the AItem class in this case, just as an implementation convenience.