/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package corejava;
/**
*
* @author Administrator
*/
public class CoreJava {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Test test=new Test();
test.setx(20);
test.printx();
Test test1=test;
test1.setx(40);
test1.printx();
test.printx();
int a=20;
int b=a;
a=40;
System.out.println(a);
System.out.println(b);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
run:
X is 20
X is 40
X is 40
40
20
Run Code Online (Sandbox Code Playgroud)
现在,当我在“a”中设置“x”的值并将对象“a”分配给“b”时,“b”将指向对象“a”的相同值。因此对“a”的任何更改也会更改“b”的值;
但是当我使用简单变量时,为什么它不像对象那样做。为什么对象存储在堆中,变量存储在栈区。
这与堆与堆栈无关,与基元与引用类型的赋值语义有关。
Java 中的对象赋值不会复制,因此Test test1=test;只会创建另一个引用内存中同一对象的“名称”(另一个变量)。
原始赋值会进行复制,因此int b=a会创建具有相同值的第二个 int,该值与第一个 int 无关。
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |