• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Access to static vs. local variables named the same

 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Consider the following code:


This seems a bit awkward to me in that you need to create an instance of a class just to access the static member variable just because it is named the same as a local variable (not saying you have to, just the way it appears from this example). You don't have to create an instance of the Math class to use the various member variables (i.e. Math.PI) so I must be missing something. Can someone describe a better way to do this?
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Chris,

Before I answer, note that this scenario seems extremely unlikely to ever come up in practice; no one who worked on any project I ran would ever be allowed to name a class variable "j"! If you use descriptive names for all variables, the chance that this would ever comes up falls roughly to zero.

But in any case, you don't need to create an object: the Math.PI syntax works fine here, too.

 
Chris Allen
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ernest,
The intent of the question was not meant to simulate a real world example. I contrived the example to make sure I understood the difference between accessing local variables, static variables, etc while studing for the Programmer exam. In any event, I agree, it is extremely unlikely to encounter in the real world but at least I will be prepared for the exam.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic