访问其他类中的变量(Java) [英] Accessing variables in other classes (Java)

查看:160
本文介绍了访问其他类中的变量(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下程序为什么不返回 0 ,因为我正在从新A()访问 p ,而该A()没有主要打电话吗?

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


推荐答案

<

可能您将 p 设为静态,然后进行了更改。现在编写的方式无法编译。

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

编辑

现在,您已更正代码,答案为:

Now that you have corrected your code the answer is:

该程序不会打印 0 ,因为您看到的是在第7行中分配的值。在这种情况下, p

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

所以当您执行时:

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

您期望看到 0 认为新A将拥有自己的 p 副本,但并非如此。

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

这篇关于访问其他类中的变量(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆