public class B {
private static boolean goo=true;
protected static boolean foo() {
goo=!goo;
return goo;
}
public String bar="Base:"+foo();
public static void main(String[] args) {
B base=new A();
System.out.println("Base:"+goo);//***prints Base:true***
}
}
public class A extends B{
public String bar="Sub:"+foo();
}
Why does the program print true instead of false, I don't understand why goo didn't change after foo() was called. goo isn't hidden because it is a private field. the static field before creating an object is true, then when foo occurs isn't it supposed to change goo in Heap?
The reason is well explained inPanz0r's answer but what you don't see is that you have two variable call
bar, one inAone inB.If you add a method to print the instance members in both class (and
Awill also print is super class):You will see that both
barexist in an instanceAYou could access
B.barvariable usingsuper.barif the accessibility allowed it but it is private in your case.A solution would be to use a constuctor
Bthat will accept a value and concatenate the result offoo.And in
AOnly the creation of
Bwill callfooso you get the result :Let's check with this :