title: Java dynamic, static casting
body: <pre><code>import javax.swing.*;
  
  public class Toast {
      static Object[] objects = { new JButton(),
          new String("Example"), new Object() };
  
      public static void main(String[] args) {
          System.out.println( new Count(objects) );
          for (Object o : objects)
              System.out.println(o);
      }
  }
  
  
  class Count {
      int b, s, o;
      public Count(Object[] objects) {
          for (int i=0; i&lt;objects.length; i++)
              count(objects[i]);
      }
      public void count(JButton x) { b++; }
      public void count(String x) { s++; }
      public void count(Object x) { o++; }
      public String toString() {
          return b + " : " + s + " : " + o + "\n";
      }
  }
  </code></pre>
  
  <p>Above is a piece of code that appears in some form or the other in past exam papers for one of my upcoming tests. The idea of the question is to gauge if you fully understand polymorphism, dynamic and static casting. Basic ideas of OO.</p>
  
  <p>I would like to put out what I think is correct and if people would be able to correct me or add points that would be greatly appreciated. </p>
  
  <p>From what I can see in the above code:</p>
  
  <ul>
  <li><p>Items are upcast to objects in the object array as every class in java technically inherits from the object class. This is why when count is run it will say there are 3 objects not 1 Jbutton, 1 string and 1 object. </p></li>
  <li><p>When the enhanced for loop is run the toString of that object type e.g. Example from the string and memory address of the object (not sure what the JButton will print). As this is done at runtime this is known as dynamic casting. </p></li>
  </ul>
  
  <p>I cannot see any other points that would be relevant to the above bit of code.</p>