首页 > 解决方案 > 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!

标签: javaclassreturn

解决方案


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

    }       

}

推荐阅读