簡體   English   中英

如何從Java中的基類方法返回派生類的對象?

[英]How to return an object of derived class from method of base class in Java?

當我運行以下代碼時,沒有錯誤

class Base {
    int x_of_base_class = 10;

    public Base print_x() {
        System.out.printf("X of Base Class = %d\n", this.x_of_base_class);
        return this;
    }

    public Base set_x(int x) {
        x_of_base_class = x;
        return this;
    }
}

class Derived extends Base {
    int y_of_derived_class = 89;

    public Derived print_y() {
        System.out.printf("Y of Derived Class = %d\n", this.y_of_derived_class);
        return this;
    }

    public Derived print_x_y() {
        print_x();
        print_y();
        return this;
    }

    public Derived set_x_y(int x, int y) {
        x_of_base_class = x;
        y_of_derived_class = y;
        return this;
    }

}

public class main_class {
    public static void main(String[] args) {

        Derived obj = new Derived();

        obj.set_x(78).print_x();

        obj.set_x_y(458, 347).print_x_y();
    }

}

但是當我使用相同的兩個類運行下面的代碼時,它給出了一個錯誤

public class main_class {
    public static void main(String[] args) {

        Derived obj = new Derived();

        obj.set_x(78).print_x_y();

    }

}

並且由於obj.set_x(78).print_x_y()產生錯誤所以,請幫我從基類返回派生類的對象

您可以使用泛型來做到這一點:

class Base<T extends Base> {
        int x_of_base_class = 10;

        public T print_x() {
            System.out.printf("X of Base Class = %d\n", this.x_of_base_class);
            return (T)this;
        }

        public T set_x(int x) {
            x_of_base_class = x;
            return (T)this;
        }
    }

class Derived extends Base<Derived> {
   ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM