Reputation: 183
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
Upvotes: 0
Views: 1136
Reputation: 11411
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> {
...
Upvotes: 1