Use Static class or abstract class to create object

So I have a general question. Suppose I want to create car objects in this program I am writing and I need to create hundreds of this car object. Is it better to create an abstract car class and extend it when I make my car (like Toyota, Nissan, etc.), or can I use a bunch of static classes that contain the details of a particular object and use them in the general car to make Toyota or Nissan? I think using an abstract method should be pretty self-explanatory, but here's an example of the second method:

public class CarNames {

public static String getCarName(int pCarIndex){

    switch (pCarIndex) {
    case 0:         
        return "Toyota";
    default:
        throw new Error("pCarIndex does not exist!");
    }
}

}

      

Used in this class to create an object:

public class Car{

    private int mCar_ID;//This indicates which Car to load
    private String mCarName;

public Car(int pCar_ID){
    mCar_ID = pCar_ID;
            mCarName = CarNames.getCarName(pCar_ID);
            //Do Stuff with collected parameters 
}

}

      

Let me know if something doesn't make sense. Thank.

EDIT: Cars can have different parameters like size, engine, etc. The reason I chose an abstract class is because I think it offers more flexibility than an interface, as I could add methods to the line.

+3


source to share


2 answers


Is it better to create an abstract car class and extend it when I make my car (like Toyota, Nissan, etc.), or can I use a bunch of static classes that contain the details of a particular object and use that in a generic car to do Toyota or Nissan?

Neither. You only have one class Car

and file (for example, a database) that contains information about a specific vehicle. Then you instantiate this class Car

based on the contents of the file.



Cars can have different parameters such as size, engine, etc.

Programmers over the past half century have called this "data". The less data you bake in the source code, the better.
+3


source


I'm going to take a stab at this ... I'm not sure if your goal in the end is ease of maintenance or memory or ... I'm going to assume that since this is an Android issue, with memory. Especially when you are talking about 100 objects.

My first thought of a fly pattern would allow these objects to share memory and have smaller prints. But I am with @CommonsWare's answer ... Part of what you are talking about is data. If I understand your question, your plan is to define all the different parts of your car in code based on the cardId, which doesn't sound very efficient. It sounds like data, be it an xml or sqllite database.



You might be talking about Nissans, which can become a type (class) extending a car of an abstract class, but all the data is about the size, height, width, and mileage of the engine.

+1


source







All Articles