上题回顾与解析
1.
//Student类中含有String name成员变量,此处在构造函数初始化name
Student stu1 = new Student("小明");
Student stu2 = stu1;
//stu1改名字
stu1.setName("小张");
思考:stu2.getName() = ?(这个问题基本不用思考,主要看第二题)
2.
Integer i1 = 1;
Integer i2 = i1;
i1 = 2;
思考:i2 = ? i2是否会跟着i1改变?为什么?
第一题:stu1和stu2指向同一对象
,stu1指向的对象中的值改变,stu2指向的对象显然也会改变。
第二题:这里需要区分stu1.setName("小张");
和i1 = 2;
的区别
stu1.setName("小张");
改变对象内成员的值i1 = 2;
相当于让i1指向一个新的对象,这里=
其实调用了Integer的valueOf(int)方法,该方法返回了一个Integer对象(相关阅读:java面试|精选基础题(2)中的1.装箱与拆箱)答案很显然了吧,执行i1 = 2
后,i1指向了另一个Integer对象,并没有也不能改变原对象的值。
每日一题
public static int test(){
int i = 1;
try{
i = 1/0;
i++;
}catch (Exception e){
return ++i;
}finally {
return i++;
}
}
思考:返回值是多少?
end~thanks!