java 变量 跨类,访问其他类中的变量(Java)

该程序中,A类的静态变量p被main方法初始化,然后在B类的go方法中尝试访问新的A实例的p。由于p是静态变量,它属于类而不是实例,因此无论创建多少个A实例,它们都会共享同一个p值。所以,程序不会打印0,而是打印main方法中赋给p的值。
摘要由CSDN通过智能技术生成

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值