title: Creating objects of a subclass as instances of the superclass in Java
body: <p>say, I have the following code (it's a quiz question, so I can run it in my IDE but the logic how it's working is not quite clear to me):</p>
  
  <pre><code>public class Test {
  
      public static void main(String[] args){
          A aInstance1 = new A();
          A aInstance2 = new B();
          A aInstance3 = new C();
          aInstance1.doSth();
          aInstance2.doSth();
          aInstance3.doSth();
      }
  }
  
  class A {
      public static void doSth(){
          System.out.println("Doing something in A");
      }
  }
  class B extends A {
      public static void doSth(){
          System.out.println("Doing something in B");
      }
  }
  
  class C extends B {
      public static void doSth(){
          System.out.println("Doing something in C");
      }
  }
  </code></pre>
  
  <p>The output will be the following:</p>
  
  <p><em>Doing something in A</em></p>
  
  <p><em>Doing something in A</em></p>
  
  <p><em>Doing something in A</em></p>
  
  <p>Thus, my first question is: what is the meaning of the declaration like</p>
  
  <pre><code>A aInstance2 = new B();
  </code></pre>
  
  <p>i.e., why to create an object of class B declaring it as an instance of class A? How the properties of aInstance2 as an object of class B change compared to the declaration</p>
  
  <pre><code>B aInstance2 = new B();
  </code></pre>
  
  <p>?</p>
  
  <p>If I remove the word <em>static</em> from the declaration of the methods doSth() in the classes A, B, and C, the output changes to </p>
  
  <p><em>Doing something in A</em></p>
  
  <p><em>Doing something in B</em></p>
  
  <p><em>Doing something in C</em></p>
  
  <p>Thus, when the methods were static, the method doSth() of class A didn't get overridden by those of the subclasses and the output was always <em>"Doing something in A"</em> produced by the objects of different classes, whereas when it became an instance (non-static) method, it gets overridden (if I'm using the right term here). Why is it so?</p>