Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › OOP III — Encapsulation, Abstraction, Enums

What is constant-specific behavior in an enum, and when would you use it instead of a switch?

Level III · MidOOP III — Encapsulation, Abstraction, Enums
Short answer

Each enum constant can supply its own method implementation by overriding an abstract method in the enum, so the behavior travels with the constant rather than living in a switch elsewhere.

Explanation

The classic example is an Operation enum where PLUS, MINUS, etc. each implement apply(). It's preferable to a switch because adding a new constant forces you to implement the behavior (the compiler enforces it), whereas a switch can silently fall through to a wrong default when a new constant is added.

Common mistakes
  • Writing a large switch over enum values in many places.
  • Forgetting that adding a constant then needs every switch updated.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for OOP III — Encapsulation, Abstraction, Enums.

Practise free

More on OOP III — Encapsulation, Abstraction, Enums