简体   繁体   中英

Can a class extended from another class use the same method with different return type?

I have an abstract class called parcel.

public abstract class Parcel implements Serializable {    
    public String type;
    public String comm;

    //The type is different for different extensions of this class, but I can't put two different types?
    public abstract void getData();

}

I then have two classes which extend that class, this is the first class...

public class singleParcel extends Parcel {

    private String info;

    public singleParcel(String comm, String infoStr) {    

        this.info = infoStr;
        super.type = "single";
        super.comm = comm;
    }    

    //This is ideally what I would like to do in this class
    public String getData() {
        return info;
    }

}

Here is the second class..

public class BigParcel extends Parcel {
    private ArrayList<Stuff> arrayOfStuff;

    public BigParcel(String comm, ArrayList<Track> arrayL) {
        this.arrayOfStuff = arrayL;
        super.type = "big";
        super.comm = comm;
    }

//This is ideally what I would like to do in this one
    public ArrayList<Stuff> getData() {
        return arrayOfStuff;
    }
}

Not sure if this is at all possible? The reason why I'd like my Parcel to be an abstract class is because I am working with a server connection. I would like there to be a package over which I can send some single piece of information over and one that I can send an ArrayList. What would be coming in would be a Parcel of either type.

You would probably need to generify the base class.

public abstract class Parcel<T> implements Serializable {    
    public abstract T getData();

public class singleParcel extends Parcel<String> {

public class BigParcel extends Parcel<List<Stuff>> {

Alternatively, you can use covariant return types, but the base type wont be as useful.

public abstract Object getData();

Generally, it is impossible this way. From syntax point of view, the signature of a method is the method name and the parameters (their types). So the returned type has to be compatible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM