Reputation: 1945
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);
}
}
Upvotes: 1
Views: 131
Reputation: 4111
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.
Upvotes: 3