Search code examples
javasubclasssuperclasstype-assertion

Assign parent class to child class variable in Java


I have a parent class and a number of child classes (let's call them parent and child1, child2, child3, etc).

I have a function which takes a 2-D array of parents and flattens it to a 1-D array like this:

public parent[] flatten(parent[][] input);

In the calling context, I know that when I pass an array, all of the elements have the same type, and that type is one of the child types (in particular, I know WHICH child type it is). I want to be able to take a particular element of the array, and assign it to a variable of the proper child type like this:

child1 c = flatten(input)[0];

I know about type assertions (relevant SO post: Assert an object is a specific type), but I can't seem to find a way to actually assign to a properly-typed variable if the assertion succeeds. Is such a thing even possible in Java? I know that it's possible in other languages, for example in Go.


Solution

  • You can't allocate generic arrays, but if you're willing to pass in an out-param you can use generics to take care of the casting for you:

     public <T extends Parent> boolean addAll(T[][] input, 
                                              T[] output) {
       //set up you indices
       output[x] = input[z];
       return true;
    }
    

    If you pass in unmatched input/output you'll get a run-time error, otherwise it should just work.