close
一. 題目
Given:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Book { | |
int id; | |
String name; | |
public Book (int id, String name) { | |
this.id = id; | |
this.name = name; | |
} | |
public boolean equals (Object obj) { //line n1 | |
boolean output = false; | |
Book b = (Book) obj; | |
if (this.name.equals(b.name)){ | |
output = true; | |
} | |
return output; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Book b1 = new Book (101, "Java Programing"); | |
Book b2 = new Book (102, "Java Programing"); | |
System.out.println (b1.equals(b2)); //line n2 |
Which statement is true?
A. The program prints true.
B. The program prints false.
C. A compilation error occurs. To ensure successful compilation, replace line n1 with: boolean equals (Book obj) {
D. A compilation error occurs. To ensure successful compilation, replace line n2 with: System.out.println (b1.equals((Object) b2));
二. 題解
建立變數 b1跟 b2的 Book物件,
兩個變數建構式的第二個參數都是 "Java Programing",
因此 b1跟 b2有相同的name,
b1有自己覆寫的equals方法,
只要參數的 name相同,就會回傳 true,
下面第3行,b1.equals(b2),
進入到上面的第11行 if (this.name.equals(b.name))
因為擁有相同的屬性 name,所以 output = true,
最後印出 true,
答案為 A。
(B) 錯誤。
(C)(D) 原參數型態為 Object型態,Object為所有物件的父類別,可接受 Book型態,可編譯成功。
三. 參考
[OCPJP]邏輯相等
文章標籤
全站熱搜