Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Just Java Chapter-6: Opinion about accessing static fields from "this" variable  RSS feed

 
Ko Ko Naing
Ranch Hand
Posts: 3178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Peter, I am extracting some portion of chapter-6 dwon below...
In methods inside the class, static data is accessed by giving its name just like
instance data.
salary = 90000;
total = this.total + this.salary;

It�s legal but highly misleading to qualify the name of a static field with �this.�
The �this� variable points to an instance, but static data doesn�t live in an
instance. The compiler knows where the static data really is, and generates code
to access the field in the class object.


Do you think accessing static field, using "this" variable or an instance of the class should be made illegal? So that the possibility to mislead the reader of the code would be low.

After reading one more page after that, I found out that some compilers generate an error if we invoke a static method through an instance variable. Even though I've been using Java for years, I didn't notice such details... So, IMO, I guess that all static-related stuff should be accessed via the class itself only, not via an instance reference. How do u think of this, Peter?

It's really good that we have great author like you here in the Ranch, clearing our doubts on Java in this week... Thanks...
 
Peter van der Linden
author
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you think accessing static field, using "this" variable or an instance of the class should be made illegal? So that the possibility to mislead the reader of the code would be low.


As you point out Ko Ko, some compilers already issue a warning when a static method is
qualified by an object reference. I think the piece that needs tightening up is the JLS - the
Java Language Specification.

It should definitely outlaw the practice of using an object reference to reach a static method or
data item. And then all compiler writers and programmers would know wher they stand.

However, this is probably not seen as a priority compared with, say, improving run time
performance. So it probably won't happen any time soon.

Cheers!

Peter
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!