在没有覆盖的情况下从Equals方法返回false

编写TestEquals class使TestEquals class main方法打印为false

注意:您不能覆盖TestEquals类的equals方法。

 public class Puzzle3 { public static void main(String[] args) { TestEquals testEquals = new TestEquals(); System.out.println(testEquals.equals(testEquals)); } } 

我没有找到实现这一目标的方法,请分享您的意见

您可能无法覆盖equals方法,但没有理由不能重载equals方法。

Object.equals方法有原型:

 public boolean equals(Object o) { ... } 

要覆盖此方法,您必须在TestEquals中创建一个具有相同原型的方法。 但是,您的问题语句表明您不允许覆盖此方法。 没问题,重载方法是完成任务的有效方法。 只需将以下方法定义添加到TestEquals:

 public boolean equals(TestEquals o) { return false; } 

而且你已经完成了。

而不是覆盖 equals,你可以重载 equals

 class TestEquals { // a common mistake which doesn't override equals(Object) public boolean equals(TestEquals te) { return 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); } } }