The Java Program: Widening.java

  1 // Widening.java -- Many OO data structures "lose" the type of subelements
  2 
  3 public class Widening {
  4 
  5    // A class "C" and a subclass "Sub"
  6    private class C {}
  7    private class Sub extends C {}
  8 
  9 
 10    C [] A;
 11    Widening (C [] x) {
 12       A = x;
 13    }
 14 
 15    C get (int i) {
 16       return A[i];
 17    }
 18 
 19    public static void main (String args[])  {
 20       final Sub [] S = new Sub [23];
 21       final Widening W = new Widening (S);  // Sub[] accepted as C[]
 22 
 23       /*
 24         The data structure "launders" the objects of type "Sub".  A
 25         narrowing is required to get the "Sub" nature of the object
 26         back.  Yet this renders the static type-checking useless.
 27       */
 28       
 29       System.out.println ((Sub) W.get (3));
 30    }
 31 }