File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Regarding behaviour static instance members Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Regarding behaviour static instance members" Watch "Regarding behaviour static instance members" New topic
Author

Regarding behaviour static instance members

Hari Kumarkar
Greenhorn

Joined: Aug 11, 2006
Posts: 19


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

Joined: Apr 06, 2010
Posts: 4369
    
    8

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

Joined: Oct 27, 2005
Posts: 19674
    
  18

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().


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Hari Kumarkar
Greenhorn

Joined: Aug 11, 2006
Posts: 19
I'm so sorry for the delay. Thanks for all who solved my problem.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Regarding behaviour static instance members