我有两个非常简单的类,一个扩展了另一个:
public class LocationType implements Parcelable {
protected int locid = -1;
protected String desc = "";
protected String dir = "";
protected double lat = -1000;
protected double lng = -1000;
public LocationType() {}
public int getLocid() {
return locid;
}
public void setLocid(int value) {
this.locid = value;
}
public String getDesc() {
return desc;
}
public void setDesc(String value) {
this.desc = value;
}
public String getDir() {
return dir;
}
public void setDir(String value) {
this.dir = value;
}
public double getLat() {
return lat;
}
public void setLat(double value) {
this.lat = value;
}
public double getLng() {
return lng;
}
public void setLng(double value) {
this.lng = value;
}
// **********************************************
// for implementing Parcelable
// **********************************************
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt (locid);
dest.writeString(desc );
dest.writeString(dir );
dest.writeDouble(lat );
dest.writeDouble(lng );
}
public static final Parcelable.Creator<LocationType> CREATOR = new Parcelable.Creator<LocationType>() {
public LocationType createFromParcel(Parcel in) {
return new LocationType(in);
}
public LocationType[] newArray(int size) {
return new LocationType[size];
}
};
private LocationType(Parcel dest) {
locid = dest.readInt ();
desc = dest.readString();
dir = dest.readString();
lat = dest.readDouble();
lng = dest.readDouble();
}
}
和:
public class MyLocationType extends LocationType {
private ArrayList<ArrivalType> mArrivals = new ArrayList<ArrivalType>();
public List<ArrivalType> getArrivals() {
return mArrivals;
}
public void addArrival(ArrivalType arrival) {
mArrivals.add(arrival);
}
}
问题是,当我将 LocationType
的实例转换为 MyLocationType
时,我得到了一个 ClassCastException .这是为什么?
最佳答案
因为 LocationType
是父类(super class);它不能转换为子类。
进一步解释一下:您只能向上转换继承树,也就是说,一个对象只能转换为它创建时的类类型、它的任何父类(super class)或它实现的任何接口(interface)。因此,String
可以转换为 String
或 Object
; HashMap
可以转换为 HashMap
、AbstractMap
Map
或 Object
>.
在您的情况下,MyLocationType
可以是 MyLocationType
或 LocationType
(或 Object
) ,但反之则不然。
Java docs on inheritance都还不错,就来这里点评一下。
关于java - 为什么我会得到这个 ClassCastException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2001827/