Enums in Karel
Our enum type ServerState
has an underlying int
type.
The possible values for ServerState
are defined as constants. Using enum
in Java, we can define these states with specific internal representation.
By implementing the toString
method, values of ServerState
can be printed out or converted to strings.
Here’s how you can do it in Java:
If we have a value of type int
, we cannot directly manipulate it as a ServerState
. This provides some degree of compile-time type safety for enums.
For example:
To run this program, save the code in Main.java
and use the javac
compiler and java
runtime:
This demonstrates how enums can be used to represent a set of named constants in Java, with the ability to add custom behavior and ensure type safety.