我有Category
类来实现Parcelable
,我还有更多的类从Category
类扩展而来。我的基类有2个protected
成员title
和id
,它们主要来自继承的类。因此,为了不在继承的类中的任何地方实现Parcelable
相关的东西,我决定在基类中执行它并让它处理所有操作。
问题是我不能拥有Category
类的构造函数,因为它是抽象类。那么解决方案是什么?由于我在类中有抽象方法,因此无法删除抽象修饰符。
public abstract class Category implements Parcelable {
private static Map<Integer, Category> categoryMap = new TreeMap<Integer, Category>();
protected Sting title;
protected Integer id;
static {
categoryMap.put(0, new Taxi());
categoryMap.put(1, new Hotel());
}
private Category(Parcel in) {
this.id = in.readInt();
this.title = in.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInteger(id);
dest.writeString(title);
}
public static final Parcelable.Creator<Category > CREATOR = new Parcelable.Creator<Category >() {
public Category createFromParcel(Parcel in) {
return new Category (in); <=== !!! THIS IS NOT ALLOWED AS CLASS IS ABSTRACT !!!
}
public Category [] newArray(int size) {
return new Category[size];
}
};
abstract void generateCodes();
abstract String getImageIcon();
};
public final class Taxi extends Category {
public Taxi() {
title = "taxi";
id = 1547845;
}
};
public final class Hotel extends Category {
public Hotel() {
title = "hotel";
id = 1397866;
}
};
答案 0 :(得分:7)
可以在抽象类中使用构造函数,并且可以在那里进行分区 - 只需确保在子类中调用相应的super(...)
方法。
检查this。
编辑: 我认为Category不需要实现CREATOR,因为你无法实例化它......?类似的建议包括here和here
public abstract class Category implements Parcelable {
private static Map<Integer, Category> categoryMap = new TreeMap<Integer, Category>();
protected String title;
protected Integer id;
static {
categoryMap.put(0, new Taxi());
categoryMap.put(1, new Hotel());
}
protected Category(){}
protected Category(Parcel in) {
this.id = in.readInt();
this.title = in.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInteger(id);
dest.writeString(title);
}
abstract void generateCodes();
abstract String getImageIcon();
};
public final class Taxi extends Category {
public Taxi() {
title = "taxi";
id = 1547845;
}
protected Taxi(Parcel in) {
super(in);
}
public static final Parcelable.Creator<Taxi> CREATOR = new Parcelable.Creator<Taxi>() {
public Category createFromParcel(Parcel in) {
return new Taxi (in);
}
public Category [] newArray(int size) {
return new Taxi[size];
}
};
};
public final class Hotel extends Category {
public Hotel() {
title = "hotel";
id = 1397866;
}
protected Hotel(Parcel in) {
super(in);
}
public static final Parcelable.Creator<Hotel> CREATOR = new Parcelable.Creator<Hotel>() {
public Category createFromParcel(Parcel in) {
return new Hotel (in);
}
public Category [] newArray(int size) {
return new Hotel[size];
}
};
};