Source of BoxNonGenericDemo.java


  1: //BoxNonGenericDemo.java
  2: //Demonstrates the BoxNonGeneric class by creating two
  3: //different class objects, one with an Integer private
  4: //data member, and one with a String private data member.
  5: //Note A cast is required when retrieving the stored value.
  6: 
  7: public class BoxNonGenericDemo
  8: {
  9:     public static void main(String args[])
 10:     {
 11:         BoxNonGeneric object1;
 12:         BoxNonGeneric object2;
 13: 
 14:         System.out.println();
 15: 
 16:         object1 = new BoxNonGeneric(123); //Autoboxing required
 17:         object1.showType();
 18:         int intValue = (Integer) object1.getObject(); //Cast required
 19:         System.out.println("value: " + intValue);
 20: 
 21:         System.out.println();
 22: 
 23:         object2 = new BoxNonGeneric("Have a nice day!");
 24:         object2.showType();
 25:         String stringValue = (String) object2.getObject(); //Cast required
 26:         System.out.println("value: " + stringValue);
 27: 
 28:         System.out.println();
 29: 
 30:         object1 = object2; //Compiles, but is conceptually wrong!
 31:         //int i = (Integer) object1.getObject();   //Compiles, but runtime error!
 32:         String s = (String) object1.getObject(); //OK, but confusing
 33:         object1.showType();
 34:         System.out.println("value: " + s);
 35:     }
 36: }
 37: 
 38: /*Output:
 39: 
 40: Type of object is java.lang.Integer
 41: value: 123
 42: 
 43: Type of object is java.lang.String
 44: value: Have a nice day!
 45: 
 46: Type of object is java.lang.String
 47: value: Have a nice day!
 48: */