Array of Objects Example              Peter Komisar



Arrays store uniform types, in this example, the reference type, Object. But Object class can
represent any reference type. Here you can see an array used to store heterogeneous objects
similar to what Vector class is designed to do. As with Vector, you still have the task of
discerning what the real type of the object is, behind the Object reference type.

We are a little ahead of ourselves here as we are using a for loop which we explain later.
The three classes A, B and C are defined at the end of the source code. Each has a method
returning a word. In the body of the ATA class, which all occupied by the main( ) method
an object array is created and an instance of each class is added to each element of the array.
For good measure, a String array is added as well.  The instanceof keyword is used in the
for loop to determine the actual type of the object stored at the element location. (Casting
could have been used as effectively).
 

class ATA{
public static void main(String[]args){

Object [] mix=new Object[ 4];

A a=new A( );
B b=new B( );
C c=new C( );
String [] s={"cat", "dog", "parrot"};

// Instances of the three classes are stored along with a String array in each element of the Object array

mix[0]=a;
mix[1]=b;
mix[2]=c;
mix[3]=s;

/* here is an example of the keyword instanceof being used to determine the specific
    type of the object represented as an Object type in the array. */

for(int i=0;i<3;i++){
  if(mix[i] instanceof A)  // selecting for the class and calling go
  System.out.print(  ((A)mix[i]).go( )  );
 
  if(mix[i] instanceof B)
  System.out.print(  ((B)mix[i]).go( )  );
 
  if(mix[i] instanceof C)
  System.out.print( ((C)mix[i]).go( )   );

  String[] sx= (String[])mix[3];      //referencing the array elements
  System.out.println(sx[i]);
  }
}
}
// three classes with a method each which return a different word

class A {
 String go( ){
  return " Bad ";
 }
}
class B {
 String go( ){
  return " Friendly ";
 }
}
class C {
 String go( ){
 return " Noisy ";
 }
}