aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static variable & Inheritance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static variable & Inheritance" Watch "Static variable & Inheritance" New topic
Author

Static variable & Inheritance

Samy Venkat
Greenhorn

Joined: May 26, 2003
Posts: 10
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.,
pinky yadav
Ranch Hand

Joined: Jun 17, 2002
Posts: 44
its printing z because variable is inherited to the subclass.
Samy Venkat
Greenhorn

Joined: May 26, 2003
Posts: 10
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 ]
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1088
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.
Prasanth James M J
Greenhorn

Joined: Jun 06, 2003
Posts: 5
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
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1088
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Static variable & Inheritance