Question 14
Back to Exercise
What is the output of the following Java program?
sealed abstract class Account permits Savings, Current {
abstract double rate();
}
final class Savings extends Account { double rate() { return 3.5; } }
non-sealed class Current extends Account { double rate() { return 0; } }
class BusinessCurrent extends Current { @Override double rate() { return 0.5; } } // allowed: Current is non-sealed
public class Main {
static String kind(Account a) {
return switch (a) {
case Savings s -> "savings";
case Current c -> c.getClass().getSimpleName().toLowerCase();
};
}
public static void main(String[] args) {
Account[] accs = {new Savings(), new Current(), new BusinessCurrent()};
for (Account a : accs) System.out.print(kind(a) + ":" + a.rate() + " ");
System.out.println();
}
}
- A savings:3.5 current:0.0 businesscurrent:0.5 Correct
- B savings:3.5 current:0.0 current:0.0
- C savings:3.5 current:0.0 current:0.5
- D Compilation error
Correct Answer: Option A
non-sealed re-opens the Current branch, yet the switch stays exhaustive because every subclass is still a Current.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!