I am pretty new to Java, so I may be using incorrect terminology. I am trying to gracefully extend a class to a new class which holds multiple instances of the superclass. For example, say I have a class
class Rose{
String smell;
Rose(String smell){this.smell=smell;}
void sniff(){ println("smells "+smell);}
}
And I want to define a class like…
class Bouquet extends Rose{
ArrayList<Rose> roses;
...
}
holding multiple roses. My actual code has something like 20 methods, and for most of them the extended method would be
void sniff(){
for( Rose one: roses) one.sniff();
}
Is there a way to construct bouquet in such a way that I don’t need to explicitly define these silly loops? I’m not tied to ArrayList, I could even make a new super class if that’s the way to go about it. However, it is important that I can send a bouquet instead of a rose argument to externally written methods.
EDIT:
Haha, I think my flower metaphor was a big fail. 🙂 But your input is good; you guys have clarified my thinking a bit.
In my real problem, there are a set of operations that define how to add instances of the base class together into a new instance of the base class. Perhaps a better metaphor would be twisting a number of small fabric strands together into one rope. External methods should treat a rope and a strand exactly the same.
It does seem like extends is wrong, any other suggestions?
You dont really need to extend bouquet from roses. You extend only when there is an IS A relationship, like you have Flower class and Rose is a Flower. But bouquet is not a rose. Ideally you should have a bouquet class which HAS many roses. If there is a 1:N relationship, then you will have to loop through to get individual items.