Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing variables in other classes (Java)

Tags:

java

class

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);
            }
        }
like image 363
George Avatar asked May 22 '26 16:05

George


1 Answers

That should not even compile.

Probably you had p as static and than you change it. The way it is written now, doesn't compile.

$ javac A.java 
A.java:7: non-static variable p cannot be referenced from a static context
            p = Integer.parseInt(args[0]);
            ^
1 error

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 p is a class variable.

 p = Integer.parseInt(args[0]);

So when you execute:

 System.out.println(new A().p);

And you expect to see 0 thinking the "new A" will have it own copy of p but is not the case.

like image 151
OscarRyz Avatar answered May 25 '26 04:05

OscarRyz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!