0

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?

2 Answers 2

1

You can use reflection.

public static <T extends A> T construct(Class<T> tClass) {
    T t = tClass.newInstance();
    t.doStuff();
    moreStuff();
    return t;
}

You may need to cast and catch exceptions, but that is the basic idea.

Sign up to request clarification or add additional context in comments.

2 Comments

This is great. What if I want to use t's constructor?
That uses the default constructor. if you want to use another constructor you need to use getConstructor()
1

You should implement factory pattern. Your implementation will use Class.forName(className).

public A create(String className) throws Exception {
    return Class.forName(className).newInstance();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.