Search code examples
javainheritanceswitch-statementgeneric-programming

Returning object depending on a value in a generic way


Consider I have many classes, that all inherit from the same class :

public class A
{
  ...
}

public class AA extends A
{
  ...
}

public class AB extends A
{
  ...
}

public class AC extends A
{
  ...
}

And then in some other part of the code, I would like to return one of the child class, depending on a value sent to that function, as follow :

public A getChild(int value, Object foo)
{
    switch(value)
    {
        case 0: {
            return new AA(foo);
        }
        case 1: {
            return new AB(foo);
        }
        case 2: {
            return new AC(foo);
        }
        default: {
          return new AA(foo);
        }
    }
}

In this example, I only have 3 types of children. But I could have let's say 30 of these, and the switch statement would become huge.

Is there any way to do the same thing using something else that a switch statement and that would be more generic? Like function pointers in C?


Solution

  • You can use a mapping of integer values to functional interfaces that create instances of the various sub-classes of A:

    Map<Integer,Function<Object,A>> map = new HashMap<>();
    map.put(0,f -> new AA(f));
    map.put(1,f -> new AB(f));
    ...
    

    Then use the mapping as follows:

    public A getChild(int value, Object foo) {
        return map.getOrDefault(value, f -> new AA(f)).apply(foo);
    }