A Java geometry program defines these classes:
class Shape { } class Rect extends Shape { int w, h; Rect(int w, int h) { this.w = w; this.h = h; } } class Square extends Rect { Square(int side) { super(side, side); } } class Circle extends Shape { int r; Circle(int r) { this.r = r; } }
Its main method runs:
Shape[] shapes = { new Square(3), new Rect(2, 5), new Circle(4), new Square(2), new Rect(1, 6) }; int total = 0; for (Shape s : shapes) { if (s instanceof Rect r) { total += r.w * r.h; } else if (s instanceof Square sq) { total += 10 * sq.w; } else if (s instanceof Circle c) { total += c.r; } } System.out.println(total);
What value does the program print? Give the answer as a whole number.
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.
Casting an array versus casting its elements
A Java media application uses these class declarations:
Each labelled case below runs independently inside a method, starting with fresh variables. Classify what happens when its two statements execute.
Typed array: