my dog learned polymorphism*
The moose likes Beginning Java and the fly likes Access to static vs. local variables named the same Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Access to static vs. local variables named the same" Watch "Access to static vs. local variables named the same" New topic
Author

Access to static vs. local variables named the same

Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
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?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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.



[Jess in Action][AskingGoodQuestions]
Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Access to static vs. local variables named the same
 
Similar Threads
class types
why I need to define a parameter variable as final?
use of super,this in static method
language fundementals
compilation fails why?