title: Overriding instance variable when moving duplicated code to superclass Java
body: <p>I'm writing a cellular automata simulation program, and I currently have several subclasses of Cell objects corresponding to each type of Simulation I want to run and each subclass has a setNeighbors method that another class calls to set the neighbors of a Cell depending on its position in the grid.</p>
  
  <pre><code>public abstract class LifeCell extends Cell{
      protected List&lt;LifeCell&gt; myNeighbors
  
      public void setNeighbors(List&lt;LifeCell&gt; neighbors){
          myNeighbors=neighbors;
      }
  
  public abstract class FireCell extends Cell{
      protected List&lt;FireCell&gt; myNeighbors
  
      public void setNeighbors(List&lt;FireCell&gt; neighbors){
          myNeighbors=neighbors;
      }
  </code></pre>
  
  <p>etc.
  The setNeighbors method is currently duplicated across subclasses and I want to move the list of neighbors into the Cell superclass as a List of abstract Cell objects. The code in my Cell superclass currently looks like this:</p>
  
  <pre><code>public abstract class Cell {
      List&lt;Cell&gt; myNeighbors;
  
      public void setNeighbors(List&lt;Cell&gt; neighbors){
          myNeighbors = neighbors;
      }
  }
  </code></pre>
  
  <p>However, it's important that the list of neighboring Cells in the subclasses be of the same type of Cell as each particular subclass (GameOfLifeCells should only have GameOfLifeCells as their neighbors). It doesn't seem like it's possible for me to declare a List of neighbors in the superclass and then override that instance variable with a list of typeCell in the subclass.</p>
  
  <p>How else would I be able to express the relation that every Cell has neighbors of the same type and still be able to access this List from the superclass?</p>