| 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: 9950
|
|
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.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
 |
|
|
subject: static method using none static variable
|
|
|