Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures - Retired Organizing Data Interfaces

Why he use `equals(other)` instead `obj.equals(other)`? when is appropriate to use it this way?

I would like to know the difference between equals(other) and obj.equals(other).

public int compareTo(Object obj){ 
    Treet other = (Treet) obj; 
    if(equals(other)) {
        return 0;
    }
}

1 Answer

Samuel Ferree
Samuel Ferree
31,722 Points

If you're inside an instance method of an object, You can call it's instance method either by themselves, or prefixed with this

See below

public class Foo {
  private Bar bar;

  // In this method, we are *inside* an instance of Foo, so we can call instance methods
  // 'this', refers to the instance we are in, so it can also be used to call instance methods
  public void printYesIfEqual(Foo that) {
    if(equals(that)) {
      System.out.println("Yes!");
    }
    if(this.equals(that)) {
      System.out.println("Yes!");
    }
  }

  // In this method, we are *inside an instance of Foo, so we have access to it's 'bar' field
  // we are not however, *inside* of Bar, so to call instance methods of Bar, on our bar field
  // we need to use the '.' operator,
  // Like before, we can also access our bar field with 'this' to refer to the object that we are *inside*
  public void printYesIfSameBar(Bar otherBar) {
    if(bar.equals(otherBar)) {
      System.out.println("Yes!");
    }
    if(this.bar.equals(otherBar)) {
      System.out.println("Yes!");
    }
}

That solve my problem, thanks.