I have a class model called "Car". If I want to create a new object of "Car" I can do something like this:
Car car = new Car();
But now, I made this class implements Parcelable. What is the best way of creating a new object of the class "Car"?
Right now I am doing this way:
Car car = new Car("blue");
And I am adding a new constructor to my model Class:
public class Car implements Parcelable {
public String color;
@Override
public int describeContents() { return 0; }
@Override
public void writeToParcel(Parcel dest, int flags) { dest.writeString(color); }
public static final Creator<Car> CREATOR = new Creator<Car>() {
public Car createFromParcel(Parcel in) { return new Car(in); }
public Car[] newArray(int size) { return new Car[size]; }
};
private Car(Parcel in) { color = in.readString(); }
public Car(String myColor) { color = myColor; }
}
Since I am new to this class Parcelable I'm not sure if this is the best aproach. Is anything bad having two constructors in my class? Is there any other more efficient way to do this?
I am afraid that adding this second constructor my application should lose some performance in creating new objects of this class.
Since I am new to this class Parcelable I'm not sure if this is the best aproach. Is anything bad having two constructors in my class? Is there any other more efficient way to do this?
It depends what you need, but your implementation of parcelable patters seems to be okey.
If u need to pass efficiently your object throught intent or arguments bundle, it is best approach. Parcelable is android more efficient implementation of class serialization.
If you want little less optimal (but easier) you could use serializable, this is default java approch, it's a bit slower, and has its own drawbacks ^^.
And if more important for you is readability of generated state (parcelable and serializable will make a byte stream from your object), you might want to use Json convertion (and for that i would suggest gson.
I am afraid that adding this second constructor my application should lose some performance in creating new objects of this class.
There is nothing wrong with multiple constructors. They are simply, a way to initialize your object state. Nothing more nothing less.
PS: For your old method of creating a car to work:
Car car = new Car();
Simply add empty constructor:
public Car() { }
Cheers.