Return false from Equals methods without overriding

Write the TestEquals classmain class method to Puzzle3print false.

Note. You cannot override the equals method of the TestEquals class.

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

I did not find a way to achieve this, please share your comments

-2
source share
3 answers

You cannot override the equals method, but there is no reason why you cannot overload the equals method.

The Object.equals method has a prototype:

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

, TestEquals. , . , . TestEquals:

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

.

+4

class TestEquals {
    // a common mistake which doesn't override equals(Object)
    public boolean equals(TestEquals te) { 
          return false;
    }
}
+3

The following will print 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);
    }
  }
}
+3
source

All Articles