Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static variable & Inheritance

 
Samy Venkat
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
its printing z because variable is inherited to the subclass.
 
Samy Venkat
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic