題目
https://www.nowcoder.com/test/question/done?tid=29883355&qid=15274#summary
解答者:https://www.nowcoder.com/profile/485624
根據下面的程序代碼,哪些選項的值返回true?
public class Square {
long width;
public Square(long l) {
width = l;
}
public static void main(String arg[]) {
Square a, b, c;
a = new Square(42L);
b = new Square(42L);
c = b;
long s = 42L;
}
}
A: a == b
B:s == a
C:b == c
D:a equal s
這題考的是引用和內存。
//聲明瞭3個Square類型的變量a, b, c
//在stack中分配3個內存,名字爲a, b, c
Square a, b, c;
//在heap中分配了一塊新內存,裏邊包含自己的成員變量width值爲48L,然後stack中的a指向這塊內存
a = new Square(42L);
//在heap中分配了一塊新內存,其中包含自己的成員變量width值爲48L,然後stack中的b指向這塊內存
b = new Square(42L);
//stack中的c也指向b所指向的內存
c = b;
//在stack中分配了一塊內存,值爲42
long s = 42L;
public boolean equals(Object obj) {
return (this == obj);
}
其實就是判斷兩個引用是否相等,故D也錯誤。