Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static method using none static variable

 
Meir Yan
Ranch Hand
Posts: 599
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 502
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12097
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic