java - Java - Return current class type
问题描述
I have a class `Num`, a class `Num2` and a `Num2` instance as follows:
public class Num {
private int num;
public Num() {
num = 0;
}
public Num add2() {
this.num += 2;
return this;
}
}
public class Num2 extends Num {}
Num2 n = new Num2();
When I use n.add2()
I get a Num
object.
How can I inherit from Num to Num2 and "change" the return type respectively?
Thank you!
解决方案
You can achieve this using the overriding and Downcasting concepts.
Sample solution:
public class Num2 extends Num{
@Override
public Num2 add2() {
return (Num2) super.add2();//Downcasting
}
}
推荐阅读
- kubernetes - 使用 cluster-admin 角色创建新的 CRD 资源
- http - 如果传输的数据多于 Content-Length(到客户端),会发生什么情况?
- php - 如何将具有整数的数组拆分为不同的格式
- python-3.x - 如何在可以随机选择的范围之外添加一个数字
- python - 从csv数据集中获取对应于一行的值
- javascript - Javascript数组到字符串的转换
- python - 我的电子邮件机器人不发送任何电子邮件并给出此错误?
- syntax - 在 julia 中查找数组的列数
- pine-script - 如何用实线绘制linebr?
- reactjs - react-beautiful-dnd 拖放不起作用