Why doesn’t the following program return 0, since I am accessing p from a new A(), which has not had main called on it?
public class A {
public static int p = 0;
public static void main(String[] args) {
p = Integer.parseInt(args[0]);
new B().go();
}
}
class B {
public void go() {
System.out.println(new A().p);
}
}
That should not even compile.Probably you had
pas static and than you change it. The way it is written now, doesn’t compile.edit
Now that you have corrected your code the answer is:
This program doesn’t print 0 because what you see is the value assigned in line 7. In this case
pis a class variable.So when you execute:
And you expect to see
0thinking the “new A” will have it own copy ofpbut is not the case.