Search code examples
javaclassmethodsthisredefinition

Java : this alone in method


Hello everybody i'm currently learning java programming and I don't understand a part of code. I searched a long time but I didn't found anything. Here is my code:

   public boolean equals(Object obj) {

  if (this == obj)
    return true;

  if (getClass() != obj.getClass())
    return false;
    
  Ville other = (Ville) obj;

  return Objects.equals(other.getCategorie(), this.getCategorie()) &&
     Objects.equals(other.getNom(), this.getNom()) &&
     Objects.equals(other.getNombreHabitants(), this.getNombreHabitants()) &&
     Objects.equals(other.getNomPays(), this.getNomPays());
}

I don't understand two parts. First:

if (this == obj)

I understand that we are trying to check something but I don't understand what? And secondly :

Ville other = (Ville) obj;

I just don't understand what it does there is no trace of a Ville class named other. This is my first Question maybe I'm not clear. Thank to all the people who will answer me :)


Solution

  •   if (this == obj)
        return true;
    

    This is the 1st check, it checks whether they are the same object (they allocate the same memory address). If this is true, it returns immediately, as they are, 100% sure, the same object.

    If this isn't the case, it goes for the 2nd check:

      if (getClass() != obj.getClass())
        return false;
    

    This checks whether they're the objects of the same class. If they are not, it returns false immediately.

    If those two conditions aren't met, it goes for the deep-check.

      Ville other = (Ville) obj;
    
      return Objects.equals(other.getCategorie(), this.getCategorie()) &&
         Objects.equals(other.getNom(), this.getNom()) &&
         Objects.equals(other.getNombreHabitants(), this.getNombreHabitants()) &&
         Objects.equals(other.getNomPays(), this.getNomPays());
    

    First it makes a cast to the type Ville, so the object obj (declared as other once casted) can call its methods (getNom(), getNombreHabitants(), etc). At this moment, it will return true if the selected parameters of the two Villes are equal.