-3

just want to ask if the class i created below is correct or if something is wrong because of the use of static list of objects and if my implementation of encapsulation in correct because i need to limit the access to my static variable.

public class Car {
    private String carName, carPlateNumber;
    private static List<Car> carList;

    public Car(String carName, String carPlateNumber) {
        super();
        this.carName = carName;
        this.carPlateNumber = carPlateNumber;
    }

    public String getCarName() {
        return carName;
    }

    public void setCarName(String carName) {
        this.carName = carName;
    }

    public String getCarPlateNumber() {
        return carPlateNumber;
    }

    public void setCarPlateNumber(String carPlateNumber) {
        this.carPlateNumber = carPlateNumber;
    }

    public static void createCarList() {
        carList = new ArrayList<Car>();
    }

    public static void addCarToList(Car car) {
        carList.add(car);
    }

    public static Car getCarAt(int location) {
        return carList.get(location);
    }

    public static void clearCarList() {
        carList.clear();
    }

    public static List<Car> getCarList() {
         return carList;
    }
}

and then to use this class like this

Car.createCarList();
Car.addCarToList(new Car("Mustang","CA-12343"));
. . .
. . .

and so on....

7
  • Why is it in Car? Feels weird that the bean you're using has a cache of itself and its other instances. Commented Sep 26, 2014 at 3:05
  • Why not use an enum instead? Commented Sep 26, 2014 at 3:09
  • Can you give me another example to implement it properly?? because i'm confuse of how can i have one instance of list of cars for other class to use. Commented Sep 26, 2014 at 3:10
  • you must separate you bean fields and caching, bean must consist of its element Car (platnumber , model , name, etc ) list of cars should be / somehow must be in the main. plus if you are using static fields, theres no need to encapsulate it (getter/setter) you should access it directly, Commented Sep 26, 2014 at 3:17
  • @agbinfo can you please elaborate on what you mean by "Why not use an enum instead?" How and why would you use an enum? Commented Sep 26, 2014 at 3:25

2 Answers 2

4

Something like the example below could be used to share your list.

The advantages of using an enum is that it provides for lazy initialization; The instance is not created until you need it. Also, when it does get initialized, it is done in a thread-safe way. You could get the same result with a class but then you'd need to synchronize the initialization some other way to make the list thread safe.

There are other ways to pass a list but when the list is global, I think that this singleton pattern is an easy and safe way to do so.

Creating the list in the main method makes it harder to reuse the list in another program. For example, if you have several lists, then you'd need to create all of them in the main method then pass them as arguments in every call or. If you have other classes refer to the Main class to access the list, as suggested elsewhere, then you create circular dependencies. The application shouldn't need to know how to create the lists required by its libraries and the libraries shouldn't need to know about the application.

public enum Cars {
  theCars;

  /* Class can be defined in a different file or defined here. 
     For example:
  public static class Car {
    public String name;
    public String make;
  }

  */

  private List<Car> cars;
  Cars() {
    cars = new ArrayList<Car>();
    cars.add(...)
  }

  // ... functions to deal with Cars
  // or simply return the entire list
  public List<Car> getList() {
    return cars;
  }
}

You can then get the cars by refering to Cars.theCars.getList()

Sign up to request clarification or add additional context in comments.

3 Comments

Please notice that the constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself. also you can not refer to the enum inside the initializer!!!! so in this case cars.add(...) is wrong. Also please fix your naming, the emum is called Cars and you are creating the list of Cars. I am assuming this is a mistake otherwise it would not make any sense at all.
@Arsham Have you tried the code above? It works fine. Cars is an enum. Cars.theCars is an instance of Cars - the only one defined. The class Car is a regular class and is not defined here. The first time that theCars is referenced it is initialized (lazy initialization) so as soon as it is referenced, the constructor is called and you can use Cars.theCars.getList() to add, remove, or otherwise access the List<Car>
@agbinfo what is the advantage of doing this? i.e. why on earth would you do this? this defeats the purpose of Enum which is: "An enum type is a special data type that enables for a variable to be a set of predefined constants." If you have a class you can create any objects as long as the values you supply to the constructor are valid then why would you use enum?
2

your bean must consist of the following element

public class Car{
   String name,platenumber,model, etc......

   //getters and setters

}

for caching purposes you can put it in your main class.

public class Main{

    public static List<Car> carList;

  public static void main(String[] args){

     //do what you want to do here
  }

}

public class OtherClassAccessCarList{

  public void someMethod(){
    //how to access static field properly
    Main.carList.add(new Car());
  }

}

ref: link1 link2

13 Comments

what is the difference between what you did and what he did in his code, the objective (I assume) is to keep list of all the objects create of type Car, why would you take out the static list and create 3 classes when you can have one. In his original implementation every time an object of type Car is built he can add it to the list if he wants. I can see what you mean by separating the list from Object definition but if someone want to cash all the created objects then he will use a proper cash. Also, now every time I need to add a Car to the list I need to remember where the list is.
@niczm25 what I am trying to say is your initial implementation was fine. I agree with him saying you don't need as setter for the list and since the list was private, getter was appropriate. The current one is also fine, except now you made the list public so everyone can access the list, that is fine if you dont mind that. If your code base is not big and you want to do bunch of stuff in main and keep track of cars there it is fine. If your code base is big and you will add to this list from different classes I would keep it in Car
@niczm25 If you put the list in Main then you get circular dependencies. Main depends on the classes it calls and these classes depend on Main. This means that the sub-classes are not reusable without Main and it should be avoided.
I THINK,it is possible you got negative vote because either the question is too simple and/or the response to it can be found with a little research. Doesnt have to do anything with your implementation.
ah, thats how it suppose to be, next time i will try, to find the right key word to search properly. btw, many thanks (bow).
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.