Frage

If I have a class Car and would also like to maintain a list of Car objects, would creating a plural class Cars be better or would it be a good practice to make static methods in the Car class to contain a list of Car?

class Car {
    private String model;
    private String color;
    ...
    private static ArrayList<Car> cars = new ArrayList<Car>();

    ...
    public Car {
        ...
        Car.cars.add(this);
    }
}
War es hilfreich?

Lösung

Usually, you would like your class to include the basic methods and attributes without knowing who is going to use it. A class Car shouldn't be aware of the application logic; thus there is no need to know that you need a List of Cars. Moreover, imagine that you need to reuse this class for another application that requires either a Map of Cars or another Collection of Cars, why to carry this unwanted List?

In your case I would divide the application logic from the class logic and create the List in a separate Class that indeed requires it.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top