| Author |
Static Instance Variables
|
RAGU KANNAN
Ranch Hand
Joined: Dec 16, 2005
Posts: 103
|
|
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. }
|
 |
Padma Lalwani
Ranch Hand
Joined: Nov 02, 2004
Posts: 49
|
|
|
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
|
 |
Asha Pathik
Ranch Hand
Joined: Feb 08, 2006
Posts: 143
|
|
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
|
SCJP 1.5
|
 |
 |
|
|
subject: Static Instance Variables
|
|
|