• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

this reference and static member

 
Jason Attin
Ranch Hand
Posts: 232
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys, if you look at this class

I would have thought that  isn't allowed because si is a static variable and it therefore doesn't have any this. Apparently this is allowed instead, and I'm not sure why that is. Any idea please?
thanks
 
Puspender Tanwar
Ranch Hand
Posts: 397
2
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes this can be used to refer any static variable. But it cannot be used in static methods.
Why it can be used with  static variable ?  Firstly what does it mean by static variable/ compile time variable ? It means a variable which belongs to a class (not to the instance) and which is available at compile time.
Instance are the runtime variable, So just think over it - if a variable is available at compile time then will it be present at runtime or not ? Ofcourse yes it will be present. And since 'this' is a instance variable and it contains the copy of all the fields present in the class, it will also contain the copy of static fields, Only difference will be that for static fields, no separate copy will be for separate intances, only one copy(original value) will be shared among all the instance.
So if I brief my answer, if a field is present at compile time, it will also be present at runtime(since it is further step of compilation). And since fields present at runtime can be accessed using 'this' , so static fields can also be accessed.

Hope it Helps
 
Ganesh Patekar
Bartender
Posts: 696
23
Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Oracle Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since static fields belong to class and there exists exactly one incarnation of the field which is shared among all objects of that class, you can refer to static fields with an object reference but not recommended as it does not make it clear that they are class variables.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic