This week's book giveaway is in the Agile forum.
We're giving away four copies of Head First Agile and have Andrew Stellman & Jennifer Greene on-line!
See this thread for details.
Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why are class and interface constants not type-safe?  RSS feed

 
Ryan McClain
Ranch Hand
Posts: 153
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Enumerations are type-safe. This is in contrast to constants that are stored in classes or interfaces.

How are these constants not type-safe? Could someone provide me with an example of this?
 
Henry Wong
author
Sheriff
Posts: 23284
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan McClain wrote:How are these constants not type-safe? Could someone provide me with an example of this?


Well, let's say you created a Directions type with the values EAST=0, WEST=1, NORTH=2, SOUTH=3.

Obviously, all Directions variables hold integer values ... but ... do all int variables hold Directions values? What happens when you compare a movement (Directions type) variable with say a numberOfWheels (integer type) variable in a Vehicle class? Will the compiler complain (as this comparison makes no sense)?

Henry
 
Ryan McClain
Ranch Hand
Posts: 153
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interesting. I suppose this would be an implementation of your example:





Correct?
 
Henry Wong
author
Sheriff
Posts: 23284
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ryan McClain wrote:Correct?

Looks good. Have a cow.

Henry
 
Ryan McClain
Ranch Hand
Posts: 153
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Mr. Wong.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!