0

I am trying to print the return value from an overriden equals method that compares the two attributes of two objects of the Tile class. In its current state this Java code yields the desired output, an accurate boolean return value that conveys if the Tile objects have identical attributes or not. Also please don't roast me over the lack of exception handling and input type checks, I'm just a novice taking it one step at a time.

public class Main {

    public static void printTile(char a, int b){
        Tile tile = new Tile();
        tile.setVars(a,b);
        Tile.printTile(tile);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        char letter = in.next().charAt(0);
        int value = in.nextInt();
        printTile(letter,value);

        Tile tile1 = new Tile();
        Tile tile2 = new Tile();
        tile1.setVars(in.next().charAt(0),in.nextInt());
        tile2.setVars(in.next().charAt(0),in.nextInt());
        boolean a = tile1.equals(tile2);
        System.out.println(a);
    }
}

And here is the equals method I wrote in the Tile class

public boolean equals(Tile that) {

    return this.letter == that.letter && this.value == that.value;
}

However, if I were to replace this

boolean a = tile1.equals(tile2);
        System.out.println(a);

with this

        System.out.println(tile1.equals(tile2));

the println method always displays the boolean value false regardless of whether the objects are identical or not. Is there a specific reason for this? Just curious and I'm not finding answers anywhere.

  • 1
    Your `equals(...)` method is not a true override since the method signature is incorrect. The signature should be `@Override public boolean equals(Object that)` not `public boolean equals(Tile that)`. Note the difference? it is key: the method parameter ***must*** be declared as type `Object` and not anything else. This is one reason that you should *always* use the `@Override` notation when trying to override methods since with the override, the compiler will tell you if your signature is wrong. – Hovercraft Full Of Eels Jul 11 '21 at 13:25
  • Side note: hopefully you're also overriding `@Override public int hashCode()` and are making sure that its behavior is correct WRT your equals method behavior – Hovercraft Full Of Eels Jul 11 '21 at 13:30
  • For a simpler test, make a constructor so you can do e.g.: Tile tile1 = new Tile('a', 1); then see how tiles compare. The result you've seen should not be possible, so your test is somehow not right. – Jool Jul 11 '21 at 13:58

0 Answers0