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

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是超类;它不能转换为子类。

进一步说明一下:您只能转换继承树,也就是说,只能将对象转换为其创建时的类类型,其任何超类或其实现的任何接口。因此,可以将String强制转换为StringObjectHashMap可以强制转换为HashMapAbstractMap MapObject

在您的情况下,MyLocationType可以是MyLocationTypeLocationType(或Object),但不能相反。

Java docs on inheritance很好,只是在这里进行评论。

10-06 06:31