Title, I am thinking something like this
Shapes s = new Shapes();
Circle c = new Circle("Our", "Parameters");
Rectangle r = new Rectangle("Our", "Parameters");
Shapes.addToList(c); // I don't want to do this for every object I create
Shapes.addToList(r);
So I want to add these object to the 'Shapes' list when I initialize a object.
Any ideas?
If Circle and Square both inherit from Shapes, then in Shapes constructor, you could automatically add to your list. In the destructor, you'd want to remove it.import java.util.*;
public class Shapes {
public static List<Shapes> allMyShapes = new ArrayList<Shapes>();
public Shapes() {
addToShapes(this);
}
static public void addToShapes(Shapes myShape) {
allMyShapes.add(myShape);
}
static public void dump() {
System.out.printf("Number of shapes stored: %d\n", allMyShapes.size());
}
}
public class Foo {
public static void main(String[] args) {
Shapes myFirstShape = new Shapes();
Circle myCircle = new Circle();
Square mySquare = new Square();
Shapes.dump();
}
}
I didn't implement the destructor. This only works, of course, if you always want this behavior.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加