Reputation: 73
I have a static variable in my Base123 class
class Base123 {
public static int statvar;
}
and I have a derived class, Inheritance111
, which extends Base123
public class Inheritance111 extends Base123 {
public static void main(String[] args) {
System.out.println(Inheritance111.statvar);
System.out.println(Base123.statvar);
Base123.statvar=10;
System.out.println(Inheritance111.statvar);
System.out.println(Base123.statvar);
System.out.println(statvar);
Inheritance111.statvar=20;
System.out.println(Inheritance111.statvar);
System.out.println(Base123.statvar);
System.out.println(statvar);
}
}
I obtained the output for above code as :
0 0 10 10 10 20 20 20
For one class, the static variable is shared across all the objects of the class. But when a class is extended, is the inherited variable in the subclass also the same variable? As the changes made using
Inheritance111.statvar=20;
is changing the value of Base123.statvar
.
Upvotes: 1
Views: 71
Reputation: 986
Yes it refers to same variable as Super class even if you call variable from sub class like Inheritance111.statvar=20;
.
You can refer to this JavaDoc static fields
Upvotes: 1