nerdexam
Oracle

1Z0-809 · Question #196

Given the code fragment: for (Course a : Course.values()) { System.out.print(a + " Fees " + a.getCost() + " "); } Which is the valid definition of the Course enum?

The correct answer is A. enum Course { JAVA(100), J2ME(150); private int cost; public Course(int c) { this.cost = c; } int getCost() { return cost; } }. Option A correctly models per-instance state by using a non-static field (private int cost) paired with an instance method (getCost()), so each enum constant - JAVA and J2ME - stores its own distinct cost value when constructed. Option B is wrong for a fundamental reason…

Question

Given the code fragment: for (Course a : Course.values()) { System.out.print(a + " Fees " + a.getCost() + " "); } Which is the valid definition of the Course enum?

Options

  • Aenum Course { JAVA(100), J2ME(150); private int cost; public Course(int c) { this.cost = c; } int getCost() { return cost; } }
  • Benum Course { JAVA(100), J2ME(150); private static int cost; private Course(int c) { this.cost = c; } static int getCost() { return cost; } }

How the community answered

(21 responses)
  • A
    81% (17)
  • B
    19% (4)

Explanation

Option A correctly models per-instance state by using a non-static field (private int cost) paired with an instance method (getCost()), so each enum constant - JAVA and J2ME - stores its own distinct cost value when constructed.

Option B is wrong for a fundamental reason: private static int cost is a single shared field across all enum constants. During initialization, JAVA(100) sets it to 100, then J2ME(150) overwrites it to 150 - meaning JAVA.getCost() would return 150, not 100. The static method compounds this by returning the same shared value regardless of which constant calls it.

A subtle trap worth noting: enum constructors in Java must be private or package-private - declaring one public (as in A) is actually a compile-time error. The exam appears to overlook this in marking A correct, focusing instead on the static vs. instance distinction.

Memory tip: Think of enum constructors like secret recipes - each constant gets its own sealed copy (private instance field), and only the enum itself can construct them (private constructor). If the field or method is static, all constants share one recipe, which defeats the purpose.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice