Given:

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;
    }
}

and the code fragment:

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));

题解

Book 类别覆写了 equals 方法,当两个 Book 对象的 name 字段逻辑相同时,则这两个对象也符合逻辑上的相同。

所以 b1 和 b2 变量所参考到的 Book 对象,有逻辑上的相同,会输出「true」。