gpt4 book ai didi

java - 处理 java 类型

转载 作者:行者123 更新时间:2023-12-01 19:01:20 24 4
gpt4 key购买 nike

java 处理所有原始类型的方式真的与自定义对象不同吗?当我检查并尝试“解释”这个简单实验程序的结果时,我提出了这个问题:

public class RandomObject {

String name;
int value;

public RandomObject(String s, int i){
setName(s);
setValue(i);
}

public int getValue() {
return value;
}

public void setValue(int value) {
this.value = value;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}


public static void main(String[] args) {

int x = 2;
int y = x;
System.out.println(y);
x = 4;
System.out.println(y);


RandomObject obj1 = new RandomObject("object1", 4);
RandomObject obj2;

obj2 = obj1;

System.out.println(obj2.getValue());
obj1.setValue(17);
System.out.println(obj2.getValue());

}

结果是:22417

虽然 x 发生了变化,但 y 的值保持不变,而在对象中,变化会影响它们两者。所有原始类型(整数除外)都会发生同样的情况吗?为什么?

最佳答案

Java确实在分配yobj2变量时处理存储在它们中的值(y = x obj2 =obj1` 分别)类似,但关键区别在于,对于对象,变量仅包含对实际对象的引用,而不是数据 -值(value)观本身。

int x,y;
x = 2;
y = x; //x = 2, y = 2
x = 3; //x = 3, y = 2 - Changing x does not change y

Object a,b;
a = new MyObject("foo"); //Create Object O on the heap, a = [Address of Object O]
b = a; //a = [Address of Object O], b = [Address of Object O]
a.updateValue("barr"); //Update a property of Object O
//a and b still contain [Address of Object O], but Object O has a new value.
a = new MyObject("Bazz"); //Create Object P, a = [Address of Object P]
//a = [Address of Object P], b = [Address of Object O]

需要注意的关键是,变量仅在存在赋值 (=) 语句时才会更新。

关于java - 处理 java 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12176234/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com