Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding behaviour static instance members

 
Hari Kumarkar
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


In above application we created a new object(a1) for class A, then it is initialized to "null", even though i can call "a1.fun() & A.fun()" and i can initialize "a1.i = 100" and "A.i = 1000"
Even after object(a1) becomes null; a1.fun() and A.fun() calls the static method fun() successfully.
We initialized to a1.i = 100 and A.i = 1000;
For a1.i = 100 and A.i = 1000 it displays 1000 as output. I want to know how its behaves and why it displays the same value as 1000.

Anticipating a positive reply.

Thanks & Regards
Hari Kumarkar
 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's how static methods and variables work. They're shared between all members of the same class. As such, it doesn't actually matter that the reference is null, because for a static method or variable the reference type is all that matters.

Because of that, though, it's considered poor practice to use instances to call static methods. Using A.fun() and A.i is much better than using a1.fun() and a1.i - you should never see the latter style in real code.

(Please UseCodeTags in future - it makes your code easier to read. I've added them this time.)
 
Rob Spoor
Sheriff
Pie
Posts: 20546
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:As such, it doesn't actually matter that the reference is null, because for a static method or variable the reference type is all that matters.

Up to Java 1.3 the following was even possible:
Nowadays it throws an ArrayIndexOutOfBoundsException, but Java 1.3 would simply ignore the entire array indexing and call A.fun().
 
Hari Kumarkar
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm so sorry for the delay. Thanks for all who solved my problem.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic