This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes static method using none static variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static method using none static variable" Watch "static method using none static variable" New topic
Author

static method using none static variable

Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
Hello all

i have simple problem here to understand something

say i have :


then i have function that need to return me the Class name but the method is static


i keep getting :

Cannot make a static reference to the non-static field cls

how can i still get the Class name in static method from none static variable ?
thanks all
Prabhu Venkatachalam
Ranch Hand

Joined: Nov 16, 2005
Posts: 502

how can i still get the Class name in static method from none static variable ?


There is no way to access non static varible in static method.

In this case If you want to access String s inside public static void getName() method, make s variable static constant public static final String s = getClass().getSimpleName(); . Because in anyways class name is not going to change.


Prabhu Venkatachalam<br />SCJP 1.4,SCWCD 1.4<br />prabhu.venkatachalam@gmail.com
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11448
    
  16

Think about it. a static method can be called when no instance of the class has ever been created.

if no instance of the class has ever been created, then what would you return?

so you might then say "well, i'll create and instance, and then the static method should return that value".

now the question becomes "what happens if i create TWO (or more) instances of the class, with different names. How does your static method know which to return?

you might say "it should return the value of the variable for the specific instance that the method was called on".

In that case, it should not be a static method.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static method using none static variable