LearnFrenzy
Sign in Take a free test

Records, Enums and Sealed Classes · Predict the Output · Question 14

A non-sealed branch with extra subclasses Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 14 Back to Exercise

What is the output of the following Java program?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links