Question about the equals function of our Piece implementation


In the Project Description, it says that the equals method should return true, if the piece type, the orientation and the point of rotation are equal.
Getting and comparing the piece type and point of rotation is straight forward, because the Piece interface has getters for them, but I’m not sure how I should compare the orientation, because it doesn’t seem like it should compare the entrie Body, just the current rotation.
I have a variable for the rotation of the piece, but that’s private to the piece implementation class and I can’t access it in the equals method.

Am I missing something here?

Thanks in advance!

Your piece implementation is the place where you should override equals. There you should have access to all necessary fields. In which class are you trying to override equals?

1 Like

Yeah, that’s what I’m doing.
I have acces to the Rotation of this Piece’s Rotation, but not of the rotation of the other objects(the one passed to the equals method) rotation.

Oops, now that you say it, it’s obvious.

Just compare bodies and do away with the rotation field. You only ever compare at most 6 array entries per call to equals, that is nothing. There is probably a way around this but it isn’t worth the effort.

I would have said that you could cast the Object to the type Piece (or PieceImplementation) after checking if it is one, after that you should also be able to access the private variables of it, as long as you try doing that in the same class as the Object is an instance of.

Edit: So the trick really is that two instances of the same class can access each others private variables.

1 Like

I did not know this, thanks! I just tested it in IntelliJ: Generating (via a context action) an equals method for a class with a private field produces a method that actually accesses the private field of the argument via a dot.

This seems fishy though, as I can also set the field without the need for a setter. :smile:

It is important to remember that visibility controls class-level access.
Therefore, inside the class, the private fields can be accessed.
Depending on the use case this can be helpful (maybe for a copy constructor for instance) or bad practice.

It is important that for cases where the attributes mentioned in the project description are observable the same for two instances, the equals method returns true and false otherwise.
What you internally check exactly and how you check it is up to your implementation.