• 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

Static Instance Variables

 
Ranch Hand
Posts: 103
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

I read the book for the following statement
�The static instance variables are accessed by static method�
But the below example non- static method accessing statis instance variable (�S�), is it possible to do like this.

13. Given the following,

1. class Test {
2. static int s;
3.
4. public static void main(String [] args) {
5. Test p = new Test();
6. p.start();
7. System.out.println(s);
8. }
9.
10. void start() {
11. int x = 7;
12. twice(x);
13. System.out.print(x + " ");
14. }
15.
16. void twice(int x) {
17. x = x*2;
18. s = x;
19. }
20. }
 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, static variable is accessible by all object instances of the class, think of it as a shared memory between objects of the same class, so static and non-static methods both can access it
 
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

void twice(int x) {
x = x*2;
s = x;
}

whenever we access instance variables from inside of a class's method it is accessed using the "this" operator. In case of non-static instance variable this signifies the current object where as in case of static variables this signifies the class for the static variable. Thus, it is possible to access static variable even from non-static context.

Asha
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic