title: Assign parent class to child class variable in Java
body: <p>I have a parent class and a number of child classes (let's call them <code>parent</code> and <code>child1</code>, <code>child2</code>, <code>child3</code>, etc).</p>
  
  <p>I have a function which takes a 2-D array of <code>parents</code> and flattens it to a 1-D array like this:</p>
  
  <pre><code>public parent[] flatten(parent[][] input);
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>child1 c = flatten(input)[0];
  </code></pre>
  
  <p>I know about type assertions (relevant SO post: <a href="https://stackoverflow.com/questions/12404650/assert-an-object-is-a-specific-type">Assert an object is a specific type</a>), 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.</p>