object construct a class of objects in java

Posted by Mgccl on Stack Overflow See other posts from Stack Overflow or by Mgccl
Published on 2011-01-09T08:31:55Z Indexed on 2011/01/09 8:54 UTC
Read the original article Hit count: 216

Filed under:

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?

© Stack Overflow or respective owner

Related posts about java