Parcelable and inheritance in Android

Vincent Mimoun-Prat picture Vincent Mimoun-Prat · Oct 29, 2010 · Viewed 22.3k times · Source

I got an implementation of Parcelable working for a single class that involves no inheritance. I have problems figuring out the best way to implement the interface when it come to inheritance. Let's say I got this :

public abstract class A {
    private int a;
    protected A(int a) { this.a = a; }
}

public class B extends A {
    private int b;
    public B(int a, int b) { super(a); this.b = b; }
}

Question is, which is the recommended way to implement the Parcelable interface for B (in A? in both of them? How?)

Answer

Vincent Mimoun-Prat picture Vincent Mimoun-Prat · Oct 29, 2010

Here is my best solution, I would be happy to hear from somebody that had a thought about it.

public abstract class A implements Parcelable {
    private int a;

    protected A(int a) {
        this.a = a;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(a);
    }

    protected A(Parcel in) {
        a = in.readInt();
    }
}

public class B extends A {
    private int b;

    public B(int a, int b) {
        super(a);
        this.b = b;
    }

    public static final Parcelable.Creator<B> CREATOR = new Parcelable.Creator<B>() {
        public B createFromParcel(Parcel in) {
            return new B(in);
        }

        public B[] newArray(int size) {
            return new B[size];
        }
    };

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel out, int flags) {
        super.writeToParcel(out, flags);
        out.writeInt(b);
    }

    private B(Parcel in) {
        super(in);
        b = in.readInt();
    }
}