Java 中的值传递和引用传递问题
public class Operation {
int data = 50;
void change(int data) {
data = data + 100;
}
public static void main(String[] args) {
Operation op = new Operation();
System.out.println("before change: " + op.data);
op.change(200);
System.out.println("after change: " + op.data);
}
}
点击查看结果
```
before change: 50
after change: 50
```
public class Operation2 {
int data = 50;
void change(Operation2 op) {
op.data = op.data + 100;
}
public static void main(String args[]) {
Operation2 op = new Operation2();
System.out.println("before change " + op.data);
op.change(op);
System.out.println("after change " + op.data);
}
}
点击查看结果
```
before change 50
after change 150
```
Dog 类
```
public class Dog {
String name;
Dog(String name) {
this.name = name;
}
String getName() {
return this.name;
}
void setName(String name) {
this.name = name;
}
String getObjectAddress() {
return super.toString();
}
}
</div>
```java
public class PassByValueExample {
public static void main(String[] args) {
Dog dog = new Dog("A");
System.out.println(dog.getObjectAddress());
System.out.println("------------------------");
func(dog);
System.out.println("------------------------");
System.out.println(dog.getObjectAddress());
System.out.println(dog.getName());
}
private static void func(Dog dog) {
System.out.println(dog.getObjectAddress());
dog = new Dog("B");
System.out.println(dog.getObjectAddress());
System.out.println(dog.getName());
}
}
点击查看结果
```
Dog@1b6d3586
------------------------
Dog@1b6d3586
Dog@4554617c
B
------------------------
Dog@1b6d3586
A
Process finished with exit code 0
</div>
```java
public class PassByValueExample2 {
public static void main(String[] args) {
Dog dog = new Dog("A");
func(dog);
System.out.println(dog.getName());
}
private static void func(Dog dog) {
dog.setName("B");
}
}
点击查看结果
```
B
```