gpt4 book ai didi

java - 从另一个类扩展的类可以使用具有不同返回类型的相同方法吗?

转载 作者:行者123 更新时间:2023-12-01 19:27:49 27 4
gpt4 key购买 nike

我有一个名为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();

}

然后我有两个类扩展该类,这是第一个类......

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;
}

}

这是第二节课..

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;
}
}

不确定这是否可能?我希望我的 Parcel 成为一个抽象类的原因是因为我正在使用服务器连接。我希望有一个包,我可以通过它发送一些单条信息,并且我可以通过它发送 ArrayList。传入的将是任一类型的包裹。

最佳答案

您可能需要泛化基类。

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

public class singleParcel extends Parcel<String> {

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

或者,您可以使用协变返回类型,但基本类型不会那么有用。

public abstract Object getData();

关于java - 从另一个类扩展的类可以使用具有不同返回类型的相同方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60960679/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com