• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Regarding behaviour static instance members

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.)
 
Sheriff
Posts: 22784
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm so sorry for the delay. Thanks for all who solved my problem.
 
reply
    Bookmark Topic Watch Topic
  • New Topic