Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Data Structures 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,721 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.