Extending a class that implements Parcelable

后端 未结 3 1900
太阳男子
太阳男子 2021-01-11 09:54

I have a class, we\'ll call it class A, that implements Parcelable.

I have a second class, we\'ll call it class B, that extends class A.

My question is:

3条回答
  •  清歌不尽
    2021-01-11 10:53

    Adding an example, the marked answer is indeed correct, but something more visual seems more suitable for this situation:

    This would be the supper class:

    public class BasePojo implements Parcelable {
    
        private String something;
    
        //what ever other constructor
    
        //getters and setters
    
        protected BasePojo(Parcel in) {
            something = in.readString();
        }
    
        public static final Creator CREATOR = new Creator() {
            @Override
            public BasePojo createFromParcel(Parcel in) {
                return new BasePojo(in);
            }
    
            @Override
            public BasePojo[] newArray(int size) {
                return new BasePojo[size];
            }
        };
    
        @Override
        public int describeContents() {
            return 0;
        }
    
        @Override
        public void writeToParcel(Parcel parcel, int i) {
            parcel.writeString(something);
        }
    
    }
    

    And then this would be the child class:

    public class ChildPojo extends BasePojo implements Parcelable {
    
        private int somethingElse;
    
        //what ever other constructor
    
        //getters and setters
    
        protected ChildPojo(Parcel in) {
            super(in);
            somethingElse = in.readInt();
        }
    
        public static final Creator CREATOR = new Creator() {
            @Override
            public ChildPojo createFromParcel(Parcel in) {
                return new ChildPojo(in);
            }
    
            @Override
            public ChildPojo[] newArray(int size) {
                return new ChildPojo[size];
            }
        };
    
        @Override
        public int describeContents() {
            return 0;
        }
    
        @Override
        public void writeToParcel(Parcel parcel, int i) {
            super.writeToParcel(parcel, i);
            parcel.writeInt(somethingElse);
        }
    
    }
    

    The marked answer provides a very good explanation, calling super is the key.

提交回复
热议问题