撰写TestEquals class
,以便Puzzle3
类的主要方法打印false
。
注意:您不能覆盖TestEquals类的equals方法。
public class Puzzle3 {
public static void main(String[] args) {
TestEquals testEquals = new TestEquals();
System.out.println(testEquals.equals(testEquals));
}
}
我没有找到实现此目的的方法,请分享您的意见
答案 0 :(得分:4)
您可能无法覆盖equals方法,但没有理由不能重载equals方法。
Object.equals方法有原型:
public boolean equals(Object o) { ... }
要覆盖此方法,您必须在TestEquals中创建一个具有相同原型的方法。但是,您的问题语句表明您不允许覆盖此方法。没问题,重载方法是完成任务的有效方法。只需将以下方法定义添加到TestEquals:
public boolean equals(TestEquals o) { return false; }
你已经完成了。
答案 1 :(得分:3)
而不是覆盖等于你可以重载等于
class TestEquals {
// a common mistake which doesn't override equals(Object)
public boolean equals(TestEquals te) {
return false;
}
}
答案 2 :(得分:3)
以下会打印false:)
import java.io.File;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
public class TestEquals {
public static void main(String[] args) {
TestEquals testEquals = new TestEquals();
System.out.println(testEquals.equals(testEquals));
}
static {
System.setOut(new CustomPrintStream(new PrintStream(System.out)));
}
public static class CustomPrintStream extends PrintStream {
/**
* This does the trick.
*/
@Override
public void println(boolean x) {
super.println(!x);
}
public CustomPrintStream(File file, String csn) throws FileNotFoundException, UnsupportedEncodingException {
super(file, csn);
}
public CustomPrintStream(File file) throws FileNotFoundException {
super(file);
}
public CustomPrintStream(OutputStream out, boolean autoFlush, String encoding)
throws UnsupportedEncodingException {
super(out, autoFlush, encoding);
}
public CustomPrintStream(OutputStream out, boolean autoFlush) {
super(out, autoFlush);
}
public CustomPrintStream(OutputStream out) {
super(out);
}
public CustomPrintStream(String fileName, String csn) throws FileNotFoundException,
UnsupportedEncodingException {
super(fileName, csn);
}
public CustomPrintStream(String fileName) throws FileNotFoundException {
super(fileName);
}
}
}