Hi anyone pls. explain why the below code prints z? class StaticVars { static char c = 'a'; } public class SuperStatic extends StaticVars { public static void main(String [] args) { StaticVars sv = new StaticVars(); SuperStatic sc = new SuperStatic(); sc.c = 'z'; System.out.println("value of c in StaticVars: " + sv.c); System.out.println("value of c in SuperStatic: " + sc.c); } } Thx.,
My question is why both of the print statements are printing 'z'. System.out.println("value of c in StaticVars: " + sv.c); System.out.println("value of c in SuperStatic: " + sc.c); The assignment to sub class variable should not affect the super class variable. Pls. explain [ June 06, 2003: Message edited by: Samy Venkat ]
Hi Samy It does so because the variable is static. There is only one static variable for any no. of instances of the class i.e. for any class instance you have the variable c refers to the one and the only c.
Static variables are always shared by all the instances no matter it is a base class instance or a child class one. So no matter we make the change in a static variable using parent class instance or a child class, it would be reflected in all its future references. PS: It is not a good practice to call static members using instance variables. To make things more clear, try this. class StaticVars { static char c = 'a'; } public class SuperStatic extends StaticVars { public static void main(String [] args) { StaticVars sv = new StaticVars(); SuperStatic sc = new SuperStatic(); //sv.c='z'; //sc.c='z'; StaticVars.c = 'z'; SuperStatic.c = 'm'; System.out.println("value of c in StaticVars: " + sv.c); System.out.println("value of c in SuperStatic: " + sc.c); } }
This would print two 'm'. ie. The last change made to the static/class variable. ~PJ
Hi Samy Prasanth gave a nice explanation. So you can and should access the static vars. as StaticVars.c. Please, if possible try to provide an output of the program if possible.
Farmers know to never drive a tractor near a honey locust tree. But a tiny ad is okay: