Java – 返回当前类类型

huangapple go评论61阅读模式
英文:

Java - Return current class type

问题

<br>
我有一个名为 Num 的类,一个名为 Num2 的类,以及一个如下所示的 Num2 实例:

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();

当我使用 n.add2() 时,我得到一个 Num 对象。<br>
我如何从 Num 继承到 Num2,并分别“更改”返回类型呢?<br>
谢谢!

英文:

<br>
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. <br>
How can I inherit from Num to Num2 and "change" the return type respectively? <br>
Thank you!

答案1

得分: 0

你可以使用覆盖和向下转型的概念来实现这一点。

示例解决方案:

public class Num2 extends Num {

    @Override
    public Num2 add2() {

        return (Num2) super.add2(); //向下转型

    }       

}
英文:

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

    }       

}

huangapple
  • 本文由 发表于 2020年10月21日 16:28:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64459659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定