Coming across a problem that I could not make a function to allow a generic return type for all the child class of a parent class.
Is there a way to create a function that allows me to return any of these children class type base on an argument?
I have the following parent class:
abstract class Number {
int res = 1;
abstract static class Builder<T extends Builder<T>> {
int res = 100;
public T setNum(int num) {
this.res = num;
return self();
}
abstract Number build();
abstract T self();
}
Number(Builder<?> builder) {
res = builder.res;
}
}
and some children class:
class One extends Number{
private int size = 1;
static class Builder extends Number.Builder<Builder> {
private int size = -1;
public Builder setSize(int size) {
this.size = size;
return self();
}
@Override
public One build() {
return new One(this);
}
@Override
protected Builder self() {
return this;
}
}
private One(Builder builder) {
super(builder);
size = builder.size;
}
}
class Two extends Number {
private String size = String.valueOf(1);
static class Builder extends Number.Builder<Builder> {
private String size;
public Builder setSize(String size) {
this.size = size;
return self();
}
@Override
public Two build() {
return new Two(this);
}
@Override
protected Builder self() {
return this;
}
}
private Two(Builder builder) {
super(builder);
size = builder.size;
}
}
Note the parent class and child classes are not done yet, but it is going to have a similar format with just more fields so this would still apply
This is something that I want to achieve:
public <T> T loadNumber(String id) {
if (id.equals('1')) {
return new ONE.Builder.build(); // this will report error right now
}
elif (id.equals('2')) {
return new TWO.Builder.build(); // this will report error right now
}
return null;
}