• Post Reply Bookmark Topic Watch Topic
  • New Topic

About static method  RSS feed

 
RajTilak Sivaluri
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am really confused about this static method .
Firstly in this public static void main() we are supposed to declare and use only static methods . But still when we declare object of another class with its object reference we can call a non static member too . What my doubt is indirectly we are calling a non static member from a static method . Why and compiler is accepting this .

Following is my doubt

 
Bharath Raja
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try to understand the static modifier .. hope kathy sierra's book will help you greatly.

members with "static" modifier have an accessible before we create the object...
 
Mohamed Sanaulla
Bartender
Posts: 3185
34
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can always call a method via the object reference and the object you have created is within the main method. You can try instantiating the same object at the Instance variable level and you can see that you will not be able to access the object reference in Main method.
 
himanshu.harish agrawal
Ranch Hand
Posts: 47
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
RajTilak,

Correct that you are calling a non static member from a static method. But compiler is not complaining because compiler knows the state at the time of calling. Aforesaid, "static" means you don't need any object (state) to access it and when you try to call a non-static members from static context then compiler doesn't know the state of that member and hence complain. But if you are telling the compiler that this is the state, by declaring object, then it becomes fine for compiler.

In short, if at the time of calling, compiler is aware about the state then it is fine for him but if he doesn't then he is gonna complain you ..

Thanks.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To put it another way.
Non-static methods must always be called using an object reference.
Using your example code it is obvious here that f is the object reference
With the other part of your code, where you just call show() it is not so obvious. However, that call is really a shorthand for
where 'this' is a reference to the current object. In a static method, 'this' doesn't have a value (because there is no current object) and so that code is illegal.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!