Tuesday, October 26, 2010

What is ArrayStoreException

An interesting situation occurs when you assign a subclass one-dimensional array variable's reference to a superclass one-dimensional array variable, because a one-dimensional array subtype is a kind of one-dimensional array supertype. If you then try to assign a superclass object reference to one of the subclass one-dimensional array's elements, anArrayStoreException object is thrown. The following code fragment demonstrates

AlarmClock [] ac = new AlarmClock [1];

Clock [] c = ac;

c [0] = new Clock ();

The compiler compiles the code fragment above because each line is legal. At runtime, however, c [0] = new Clock (); results in an ArrayStoreException. That exception occurs because we might try to access an AlarmClock-specific member via a reference to a Clock object. For example, suppose AlarmClock contains a public void soundAlarm() method, Clock lacks that method, and the code fragment above executes without throwing anArrayStoreException object. An attempt to execute ac [0].soundAlarm (); crashes the JVM because we attempt to execute that method in the context of a Clock object (which doesn't incorporate a soundAlarm() method).

No comments:

Post a Comment