-2

编写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));
    }
}

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

4

3 回答 3

4

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

方法 Object.equals 有原型:

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

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

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

你完成了。

于 2012-08-28T09:15:51.640 回答
3

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

class TestEquals {
    // a common mistake which doesn't override equals(Object)
    public boolean equals(TestEquals te) { 
          return false;
    }
}
于 2012-08-28T09:13:55.177 回答
3

以下将打印错误:)

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);
    }
  }
}
于 2012-08-28T11:11:43.493 回答