A Java media application uses these class declarations:
class Asset {} class Photo extends Asset {} class Audio extends Asset {}
Each labelled case below runs independently inside a method, starting with fresh variables. Classify what happens when its two statements execute.
Typed array:
Asset[] items = new Photo[2]; Photo[] photos = (Photo[]) items;
Broad array:
Asset[] items = new Asset[] {new Photo(), new Photo()}; Photo[] photos = (Photo[]) items;
Single element:
Asset[] items = new Asset[] {new Photo(), new Photo()}; Photo photo = (Photo) items[0];
Different asset:
Asset[] items = new Photo[2]; items[0] = new Audio();
Null element:
Asset[] items = new Photo[2]; items[0] = null;
Enter exactly OK if both statements complete normally, CAST if execution throws ClassCastException, or STORE if execution throws ArrayStoreException. All five cases compile.
Unlock full course notes by signing up
What an upcast does and does not change
A Java music app defines the following classes and then executes Media m = new Song();.
Select all of the statements below that are true.
Classifying cast outcomes in a bank hierarchy
A Java banking program defines these classes:
It then declares Account a = new Premium(); and Savings s = new Savings();. Treat each statement in the table on its own, as if it were the only statement after these two declarations. In the Outcome column, type OK if the statement compiles and runs, COMPILE if the compiler rejects it, or RUNTIME if it compiles but throws a ClassCastException.
Tracking stock after reference reassignment
A warehouse program uses the following Java classes to track the number of kits in a stock record:
The following statements execute in order inside a method:
Determine the final number of kits accessed through saved, the final number of kits accessed through (KitStock) current, and the number of KitStock instances created by the shown new expressions. Give the first two quantities in kits and all three answers as exact integers.
Tracing instanceof tests in a shape loop
A Java geometry program defines these classes:
Its main method runs:
What value does the program print? Give the answer as a whole number.