java - Consider the following program written in Java. why this output **2 2**. I think this should be output **1 1**
问题描述
Consider the following program written in Java. Why is the output 2 2? I think it should output 1 1
class Access{
static int x;
void increment(){
x++;
}
}
public class Main{
public static void main(String args[])
{
Access obj1 = new Access();
Access obj2 = new Access();
obj1.x = 0;
obj1.increment();
obj2.increment();
System.out.println(obj1.x + " " + obj2.x);
}
}
解决方案
静态变量在类的所有实例之间共享,当我们需要进行内存管理时它们很有用。在某些情况下,我们希望所有实例都有一个共同的值,比如全局变量,那么最好将它们声明为静态,因为这样可以节省内存(因为只为静态变量创建单个副本)。
因此,当调用 obj1.increment() 时,它会将 x 的值更新 1。当调用 obj2.increment() 时,它会将相同的静态引用更新 +1 并使其变为 2。最后,ypu 将两个值都设为2. 下面的代码片段会将值打印为 1 和 2。
obj1.increment();
System.out.println(obj1.x);
obj2.increment();
System.out.println(obj2.x);
推荐阅读
- node.js - 在异步应用程序中定义解析/拒绝的正确方法是什么
- javascript - 根据逾期天数发出警报的基本 Netsuite 客户端脚本
- c - 在同一个源上多次运行 C 预处理器是否安全?
- javascript - 使用公司名称查找准确的linkedin url
- excel - 如何跨多个工作表对表格进行排序?
- javascript - javascript 类方法的调用比相同的函数慢 20-40 倍
- python - 有谁知道为什么 request.get() 函数可能不起作用
- java - 为什么 javax.annotation.processing.AbstractProcessor.init 经常“同步”?
- reactjs - React 如何创建带有反应路由器的子页面来显示?
- python - 是否可以将值添加到 for 循环中?