为什么我得到这个ClassCastException?

Jer*_*gan 2 java casting

我有两个非常简单的类,一个扩展另一个:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

和:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是当我转换一个实例时LocationType,MyLocationType我得到一个ClassCastException.为什么是这样?

del*_*ego 7

因为LocationType是超类; 它不能转换为子类.

进一步解释一下:你只能编译继承树,也就是说,一个对象只能被转换为它创建的类类型,它的任何超类,或者它实现的任何接口.因此,a String可以被铸成a String或a Object; a HashMap可以演员为a HashMap,an AbstractMap Map或an Object.

在你的情况下,a MyLocationType可以是a MyLocationType或a LocationType(或an Object),但不是相反.

关于继承Java文档非常好,只需在这里查看.