LearnFrenzy
Sign in Take a free test

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

Enums implementing an interface Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
import java.util.List;

interface Priced { int price(); }

enum Size implements Priced {
    SMALL(150), MEDIUM(220), LARGE(290);
    private final int p;
    Size(int p) { this.p = p; }
    public int price() { return p; }
}

enum Extra implements Priced {
    CHEESE { public int price() { return 40; } },
    OLIVES { public int price() { return 30; } };
}

public class Main {
    public static void main(String[] args) {
        List<Priced> order = List.of(Size.LARGE, Extra.CHEESE, Extra.CHEESE, Extra.OLIVES);
        int total = order.stream().mapToInt(Priced::price).sum();
        System.out.println(total + " " + order);
    }
}
  • A 400 [LARGE, CHEESE, CHEESE, OLIVES] Correct
  • B 390 [LARGE, CHEESE, OLIVES]
  • C 400 [Size.LARGE, Extra.CHEESE, Extra.CHEESE, Extra.OLIVES]
  • D Compilation error
Correct Answer: Option A

Different enums can be handled together through a shared interface. 290 + 40 + 40 + 30 = 400.

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