0

I am learning a java language.I have a question , how enum is type safe in java.

public enum Direction {EAST,WEST,NORTH,SOUTH;}

How enum Direction is type safe? Please help me.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • Type safety means that a program cannot perform an operation on an object unless that operation is valid for that object. – whyn0t Aug 26 '16 at 16:42

1 Answers1

2

Let's compare your Direction enum with a plain String alternative.

A user can only pass a valid enum or null into any method. You're guaranteed to get NORTH, SOUTH, EAST, or WEST.

If you use a String instead you can get blank, "Foo", or any other thing that the user decides to pass.

An enum spells out the correct values and limits what you get. MUCH safer.

duffymo
  • 305,152
  • 44
  • 369
  • 561