If I wanted to take the class StoreInventory and its attributes and use those attributes in a new class how do I include the StoreInventory in my new class Snacks?
-
2As this is homework, I feel as if this topic should had been previously discussed in your text-book of some sort. I would advise you to review and see if you can figure it out, try out some code and if it doesn't work respond back with any problems you come across.Anthony Forloney– Anthony Forloney2013-01-27 18:26:18 +00:00Commented Jan 27, 2013 at 18:26
-
I've removed the homework tag since it has been deprecated. Please click the tag link to see that it has been marked obsolete and why.Hovercraft Full Of Eels– Hovercraft Full Of Eels2013-01-27 18:32:34 +00:00Commented Jan 27, 2013 at 18:32
5 Answers
You state:
If I wanted to take the class StoreInventory and its attributes and use those attributes in a new class how do I include the StoreInventory in my new class Snacks?
Your logic doesn't smell right to me. Wouldn't it be the other way around -- StoreInventory should hold Snack objects and not be Snack objects holding StoreInventory objects?
Note that whatever you do, and no matter what folks suggest, inheritance is not the solution you want. Use composition, and likely your StoreInventory object should hold either an array of Snack or a collection such as an array list of Snack -- ArrayList<Snack>.
e.g.,
public class StoreInventory {
private List<Snack> snackList = new ArrayList<Snack>();
// ... etc...
public void addSnack(Snack snack) {
snackList.add(snack);
}
}
Comments
Two standard ways:
Aggregation: You have a
StoreInventorydata member within your class definition and use it. E.g.:class Snacks { private StoreInventory inventory; Snacks() { this.inventory = new StoreInventory(); } }Inheritance: You derive from
StoreInventory, e.g.:class Snacks extends StoreInventory { Snacks() { super(); // <== Initialize the base class } }Note that the call to
super();doesn't have to be explicit if there are no arguments; if you leave it out, the compiler will add it for you. But ifStoreInventoryneeds construction arguments, that's how you would supply them.
Now you have the terminology, you shouldn't have much trouble finding tutorials for those two concepts.
Comments
You can use either inheritance
class Snacks extends StoreInventory
or composition (most likely this one in your case):
class Snacks {
private final StoreInventory storeInventory = new StoreInventory();
}
Although without more information, it's hard to say which would be better, but those are basically your two choices.
Comments
You can either extend the StoreInventory class or include it as a field in the new class.
These techniques are called inheritance and composition respectively.
See this: http://www.artima.com/objectsandjava/webuscript/CompoInherit1.html