title: How to store an object of variable type in a field in Java?
body: <p>I have created an object in Java, called "Edge". This object is a directed edge for a graph that stores a reference to the node at its start and the node at its end.</p>
  
  <p>These nodes are currently a "Vertex" object, however I would like to also store the origin of the dual edge in the same object, so that it would return a "Face" object instead. Currently I only support returning a Vertex, as shown in the code below.</p>
  
  <pre><code>public class Edge{
  
      private Vertex org; //this is the line that I want to be able to store a 
                          //face given certain conditions (the index being 1 or 3)
  
      private Face left;  //this is a line where I want to store a face normally
                          //but store a Vertex if this is a dual edge
  
      private int index;  //a number from 0-3, where 1 and 3 are in the dual graph
  
      public Vertex Org(){
          return org;
      }
  
  }
  </code></pre>
  
  <p>I was wondering if there was a way of defining the function Org() and the field org, in such a way that the it could either be a Face or a Vertex. I was wondering if there was a way of using generic types, that could take become a "Vertex" or a "Face" depending on the index parameter. An example of what I tried is below.</p>
  
  <pre><code>public class Edge&lt;T&gt;{
  
      public T org;
  
      private T Org(){
          return org;
      }
  
  }
  
  </code></pre>
  
  <p>However, this does not seem a very elegant solution and it only works for getting the origin and not the left Face/Vertex.</p>
  
  <p>I was wondering if there was a way of storing a field that can be one of two possible object types, or another simple way of getting around this problem.</p>