/*File Dynamic2.java Copyright 1997, R.G.Baldwin Illustrates instantiation of array of references of type Object and the use of that array to refer to objects of an inherited class. The output from this program is as follows: myArrayOfRefs contains Dynamic2@1cc738 Dynamic2@1cc739 Dynamic2@1cc73a Objects referred to by myArrayOfRefs contain 13 14 15 ********************************************************/ class Dynamic2 { //single instance variable of the class of type int private int objData; //parameterized constructor public Dynamic2(int inData){ objData = inData; }//end constructor //get method public int getData(){ return objData; }//end getData() public static void main(String[] args){//main method //Instantiate array of references to objects of type // Object in dynamic memory at runtime. Object[] myArrayOfRefs = new Object[3]; //Instantiate some objects of type Dynamic2 in // dynamic memory and store references to those // objects in the array of references of type Object. for(int i = 0; i < 3; i++) myArrayOfRefs[i] = new Dynamic2(i+13); //Display the values contained in the array of // references to objects. Note that the values // identify the actual type of object referred to. System.out.println("myArrayOfRefs contains "); for(int i = 0; i < 3; i++) System.out.println(myArrayOfRefs[i]); System.out.println(); //Display the values in the objects referenced by // the array of references. Note the requirement // to downcast the references to the actual type // of object referred to by the references in // order to access the instance variables of the // objects. System.out.println( "Objects referred to by myArrayOfRefs contain "); for(int i = 0; i < 3; i++) System.out.println( ((Dynamic2)(myArrayOfRefs[i])).getData()); }//end Main }//End Dynamic2 class definition.