title: Beginner Array of Objects Confusion
body: <p>I am having trouble understanding what is actually happening when I declare the array in the following code. </p>
  
  <pre><code>class Type1 {
  
  }
  
  class Type2 extends Type1 {
      public void method2() {
  
      }
  }
  
  class Test {
      public static void main(String[] args) {
  
          Type1[] x = new Type2[2];
          x[0] = new Type1(); // runtime error
          x[1] = new Type2();
          x[1].method2(); // syntax error
  
      }
  }
  </code></pre>
  
  <p>I thought since the right-hand side of the array declaration is <code>new Type2[2]</code> that the array would consist of reference variables of the type <code>Type2</code>. If this is true, the first error makes sense because I cannot have a subtype referring to a supertype.</p>
  
  <p>However, why does the second error occur two lines after that? Isn't <code>method2()</code> known by Type2, so the method is known by the reference variable? It seems it is because <code>Type1</code> doesn't know <code>method2</code>, so does that mean the array consists of reference variables of the type <code>Type1</code>? If this is true, why does the first error occur as it is no longer a subtype referring to a supertype?</p>
  
  <p>Also, why is the first error a runtime error while the other is a syntax error?</p>
  
  <p>Please note I am only in my second programming course, so my terminology may be a little off. </p>
  
  <p>Edit: The question <a href="https://stackoverflow.com/questions/16914132/arraystoreexception-when-trying-to-set-an-element-of-an-array-to-a-superclass-ob">here</a> does not answer my question because it does not answer why an element of an array like <code>x</code> cannot invoke <code>method2()</code> even though an element of <code>x</code> of <code>Type 2</code>. My question is different because of this and because my question also asks why the first error occurs when the second error also occurs (why an element of <code>x</code> cannot refer to and object of the type <code>Type1</code> and at the same time cannot invoke <code>method2()</code>). I originally thought that if one error occurred, then the other cannot occur. I wanted a comparison between the two errors and a more in-depth explanation than simply the rules of polymorphism. </p>