• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Why are class and interface constants not type-safe?

 
Ranch Hand
Posts: 153
1
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
author
Posts: 23928
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Interesting. I suppose this would be an implementation of your example:





Correct?
 
Henry Wong
author
Posts: 23928
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Mr. Wong.
 
Squanch that. And squanch this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic