Java Reference
In-Depth Information
You need to perform a cast at the time you read back the object from the array, as shown:
/* Compiler will flag an error for the following statement. genericArray is of Object type and an
Object reference cannot be assigned to a String reference variable. Even though genericArray[0]
contains a String object reference, we need to cast it to String as we do in next statement.
*/
String s = genericArray[0]; // A compile-time error
String str = (String)genericArray[0]; // Ok
Person p = (Person)genericArray[1]; // Ok
Account a = (Account)genericArray[2]; // Ok
If you try to cast the array element to a type, whose actual type is not assignment compatible to the new type, a
java.lang.ClassCastException is thrown. For example, the following statement will throw a ClassCastException
at runtime:
String str = (String)genericArray[1]; // Person cannot be cast to String
You cannot store an object reference of the superclass in an array of the subclass. The following snippet of code
illustrates this:
String[] names = new String[3];
names[0] = new Object(); // An error. Object is superclass of String
names[1] = new Person(); // An error. Person is not subclass of String
names[2] = null; // Ok.
Finally, an array reference can be assigned to another array reference of another type if the former type is
assignment compatible to the latter type.
Object[] obj = new Object[3];
String[] str = new String[2];
Account[] a = new Account[5];
obj = str; // Ok
str = (String[]) obj; // Ok. Because obj has String array reference
obj = a;
// ClassCastException error. obj has the reference of an Account array and
// an Account cannot be converted to a String
str = (String[]) obj;
a = (Account[]) obj; // Ok
Search WWH ::




Custom Search