Aaron
Aaron

Reputation: 151

An equals method when the parameter is of type object

I'm learning Java and am having some trouble with casting/polymorphism concepts.

If I have the following method:

public boolean equals(Object x);

Where x could reference an Object of Class Y;

What's the best way to see if x equals y (a variable referencing an obj of Class Y) ? I understand downcasting e.g. (Y) x is bad?

Upvotes: 0

Views: 101

Answers (3)

somejavaexpert
somejavaexpert

Reputation: 1

It highly depends on your interpretation of equality. That's why the equals operator can be overridden.

Just do x.equals(y) and do the interpretation of equality by overriding the equals method.

One template method for this is to do:

public boolean equals(Object x) {
  if (this == x)
    return true;
  if (x == null || this.getClass() != x.getClass())
    return false;
  // Compare attributes as needed here
}

Of course you should check if x != null before, if there are chances it is null.

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200206

Downcasting is the norm in Object.equals. Before downcasting, check that x is indeed a compliant object with x instanceof Y; to ensure the symmetry of equals, a check x.getClass() == this.getClass() will be necessary at times.

If x is not an instance of your class, you immediately return false.

Upvotes: 3

Mena
Mena

Reputation: 48434

Downcasting is not bad if you firstly perform the following checks:

  1. Check for null --> x != null
  2. Compare classes at runtime --> getClass().equals(x.getClass())

Then you can downcast x as the class of this, and perform specific comparisons.

Prior to your null check, you may also want to compare references of this and x.

If the references are equal, you don't need to perform any other comparison.

Upvotes: 1

Related Questions