开发者

Accessing variables in other classes (Java)

开发者 https://www.devze.com 2022-12-30 14:20 出处:网络
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?

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 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.


That shouldn't even compile, since you're trying to assign an instance member from a static method.


This program doesn't compile. The compiler won't let you access 'p' from within the main method of class A. You cant access non static variables from within a static context. Hence the compilation issue


That won't compile as is, so I don't know how it would return anything.

Variable p cannot be accessed from a static context is what it SHOULD say.

If you set an instance of p, it should work correctly.

ps. For this one experiment I will let you have a public non-final member variable, but NEVER AGAIN!


EDIT: this was just a guess based on the first revision of the question, which assumes p is non-static. It turns out that the intent was that it is static, so this gets the wrong end of the stick.

Despite the compiler error, I assume your intent was to initialize p from a non-static method, or on an instance of A.

The problem is then that you are creating a new instance of A in B, and not using the original instance.

To get what (I believe) you want, do something like

   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);
            }
        }

Note that the go() method in B takes A as a parameter. No new instance of A is created.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号