문제

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);
    }
}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top