0

So I have this problem that I want to have a factory / manager class UserManager that manages Users. And Users have both UserType1 and UserType2 extending to it.

currently I have this for UserManager.

public abstract class UserManager<T extends User> {
    // T is either UserType1 or UserType2
    public ArrayList<T> users;
}

Now I want to create UserType1 or UserType2 depending on conditions, e.g.

public T create(boolean isType1) {
    if(isType1) // create UserType1
    else // create UserType2
}

And I can't just do

T newUser = new T();

I'm stuck, any help is appreciated!!

  • 1
    It seems you can always replace T by User, don't need generic here – azro Jul 12 '18 at 12:32
  • Maybe related to of [Generic factory with unknown implementation classes](https://stackoverflow.com/questions/6093363/generic-factory-with-unknown-implementation-classes) – LuCio Jul 12 '18 at 12:37

1 Answers1

0
public T create(boolean isType1) {
    if(isType1) // create UserType1
    else // create UserType2
}

This doesn't make sense: what happens if T is UserType1 and isType1 is false? Then you would create a UserType2 which isn't a T.

If isType1 is fixed for a given UserManager then it shouldn't be a parameter in the first place, and you can have

abstract public T create();

with different implementations or cheat with casts (bad idea, generally speaking).

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • UserType2 also extends User. Since T extends User, UserType2 could be a T right? – George Huang Jul 12 '18 at 13:22
  • No. Think this way: inside `UserManager` `T` is some fixed type extending `User`, but you don't know which: it could be `UserType1`, `User`, some other subclass you don't know about, etc. Your code must make sense for any of those possible `T`s. So the problem is that `UserType2` could be _not_-a-`T`. – Alexey Romanov Jul 12 '18 at 13:31