Access to variables in other classes (Java)

Why doesn't the following program return 0 , since I am accessing p from a new A () that was not main ?

 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);
            }
        }
+3
source share
5 answers

It should not even compile.

You probably had it pas static, and you changed it. The way it is written now does not 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

Strike>

change

Now that you have adjusted your code, the answer is:

This program does not print 0 , because what you see is the value assigned on line 7. In this case, it pis a class variable.

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

, :

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

0, , " A" p, .

+2

, .

0

. "p" A. . ,

0

, , - .

p - , .

p, .

. -, !

0

EDIT: , , , p . , , , .

, , p A.

, A B .

, ( ), , -

   public class A {

         public int p = 0;

         public static void main(String[] args) {
                A a = new A();
                a.p = Integer.parseInt(args[0]);
                new B().go(a);
         }

   }


       class B {
            public void go(A a) {
                System.out.println(a.p);
            }
        }

, go() B A . A.

0

Source: https://habr.com/ru/post/1746098/


All Articles