简体   繁体   中英

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

When I'm running the below code there is no Error

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

}

But when I'm running the below code with the same two classes it is giving an error

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

        Derived obj = new Derived();

        obj.set_x(78).print_x_y();

    }

}

And Error is generated because of obj.set_x(78).print_x_y() So, please help me to return the object of derived class from base class

You can use generics to do this:

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> {
   ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM