public class People {
int age = 20;
public void change(People people) {
people = new People();
people.age = 30;
System.out.println("chang()"+people.age); }
public static void main(String[] args) {
People people = new People();
int age = people.age;
System.out.println(age+"---");
people.change(people);
int age2 = people.age;
System.out.println(age2+"++");
}
增加一行代码:
打印结果:
20---
chang(): 30
20++
int age = people.age;System.out.println(age);
nt age2 = people.age;System.out.println(age2);
这两行代码是一样的。都是打印定义的变量20.
打印结果是:
20
20
——————————
而不是20和30
原因在于题中
public void change(People people) {
people = new People();
people.age = 30;
}
方法中传进去的people对象已经被重新赋值为一个新的People对象,所以里面的30是赋值给了一个新的对象,而那个新的对象也叫做People,所以造成误导,此时在方法内部打印People的age变量就是30了
把代码改变一下
public class People {
int age = 20;
public People change(People people) {
people = new People();
people.age = 30;
return people;
}
public static void main(String[] args) {
People people = new People();
int age = people.age;
System.out.println(age);
people= people.change(people);
int age2 = people.age;
System.out.println(age2);
}
}
此时在运行结果就是20和30
public class People {
int age = 20;
public void change(People people) {
people = new People();//5. 5.1:people局部变量接受主函数传递过来的对象。5.2:new People是建立一个新对象把地址值赋给people,people现在的对象引用是这个方法里面新建的对象。和主函数所创建的对象没有关系
people.age = 30;//6.修改新对象的age。以前对象的age没有关系
}
public static void main(String[] args) {
People people = new People();//1.创建一个对象,对象进行初始化
int age = people.age;//2.调用people对象的成员变量age值赋值给main函数局部变量age
System.out.println(age);//3.打印main函数变量age值 输出“ 20 ”
people.change(people)//4.调用people对象的方法change,传递一个对象
int age2 = people.age;//7.调用people对象的成员变量age值赋值给main函数局部变量age,他的age值没有改变过
System.out.println(age2);//打印age值:“ 20 ”
}
}
输出结果:
20
20