object construct a class of objects in java
- by Mgccl
There is a super class, A, and there are many subclasses, B,C,D... people can write more subclasses. Each of the class have the method dostuff(), each is different in some way.
I want an object that constructs any object that belong to A or any of it's subclass.
For example I can pass the name of the subclass, or a object of that class, and it will construct another object of the class.
Of course I can write
A construct(A var){
stuff = var.dostuff();
domorestuff(stuff)
return new A(stuff);
}
B construct(B var){
stuff = var.dostuff();
domorestuff(stuff)
return new B(stuff);
}
C construct(C var){
stuff = var.dostuff();
domorestuff(stuff)
return new C(stuff);
}
but this is not efficient. I have to write a few new lines every time I make a new subclass.
It seems I can't use generics either. Because I can't use dostuff() on objects not in any of the subclass of A.
What should I do in this situation?