LearnFrenzy
Sign in Take a free test

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

Constants that implement an abstract method Answer, explanation & discussion

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

What is the output of the following Java program?

Main.java
enum Shipping {
    STANDARD { double cost(double kg) { return 40 + 10 * kg; } },
    EXPRESS  { double cost(double kg) { return 2 * STANDARD.cost(kg); } },
    PICKUP   { double cost(double kg) { return 0; } };

    abstract double cost(double kg);
}

public class Main {
    public static void main(String[] args) {
        for (Shipping s : Shipping.values()) System.out.print(s + "=" + s.cost(2.5) + " ");
        System.out.println();
    }
}
  • A STANDARD=65.0 EXPRESS=130.0 PICKUP=0.0 Correct
  • B STANDARD=65.0 EXPRESS=65.0 PICKUP=0.0
  • C STANDARD=50.0 EXPRESS=100.0 PICKUP=0.0
  • D Compilation error
Correct Answer: Option A

Each constant supplies its own cost(); EXPRESS reuses STANDARD's.

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