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 Local Development Environments Advanced Tooling Code Generation

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Why we override toString() and equals() and use this methods???

Can someone explain me that please?

3 Answers

Kevin Faust
Kevin Faust
15,353 Points

Hey Grigorij,

I didnt really explain toString() in depth in my above answer so let's dive into it Let's take a look at your example. I recommend you use a workspace/ide and paste this code in so you can see this for yourself.

Let's say we have an empty class object. Inside it there is only the toString() method

public class Cat {

/*@Override
public String toString(){
     return "Look at me! Im a cat object!";      
}

Run this program with this code commented out. And then run it again with it uncommented

*/
}

And let's say this is our main class:

public class UnderstandingToStringMethod{

public static void main(String[] args) {

   Cat catObject = new Cat();
   System.out.println(catObject);

}
}

I think the best way for you to see this is to experience it yourself. create a new one or use a old one but just temporarily delete all the code on it and use the code above and then run it.

In case you cant, ill tell you what happens. As you can see we have a blank cat class. When we create the cat object in our main file and then we print out that object to the console, do you know what appears. The cat object is NOT a string so what on earth would be printed to the console. It will print out this: Cat@7852e922

You may be wondering, what is that and why is that printed. Well simple. That is the location of where the object is stored in java. Since we dont have a string representation of that objet, the only thing it can print out is that memory location.

Now what happens if we uncomment that toString() method? Well, when we print out the object, BEFORE printing out the memory location, it will check that object to see if it has a toString() method and then we use that string text instead of the memory location. That's why we put @override because we are in fact overriding the default memory location text.

Let's take a look at what you wrote here:

//So we have to define the method toString() to prevent errors in the returnObject method ???

Nope it doesnt prevent errors as we can print out the memory location with no problem. But toString() is to change that memory location text to our specified text. Remember objects are not strings.

If you still dont understand what im saying, i encourage you to try it yourself and you will for sure completely understand.

If this helped and you understand, please mark as best answer so others can see this as well.

Thanks and happy coding!

Kevin

Kevin Faust
Kevin Faust
15,353 Points

Here is my workspace that i used and you can just fork it:

https://w.trhou.se/iptjwz6mre

Kevin Faust
Kevin Faust
15,353 Points

Hey Grigorij,

lets start off with reminding ourselves that the toString() and the equals() method are both from the object class so everything has these two methods. Ok lets get into the explanation:

remember before that if we tried to call an object as a string, it would bring back a bunch of mumbojumbo? We use the toString() method in an object to define what we want that object to be known as in string format. So if we were to call an object as a string, that toString() method will be automatically called and will return what we wrote inside that method.

and for equals(), we use that to determine what exactly our objects need for them to be equal to each other. If we compare two objects, what is "equal"? Lets look at an example:

public class Employee {
  ...
  public boolean equals(Object o){
    if(o == null)                return false;
    if(!(o instanceof) Employee) return false;

    Employee other = (Employee) o;
    return this.employeeId == other.employeeId;
  }
}

so we have an employee class with a equals method inside it. If the object we pass in is null, then, well, its not even an object so we return false. Now once we make sure that it is indeed an object, we check whether both the classes are the same which makes sense because we cant compare an employee and customer object as they are completely different. Then we simply downcast it and store it as a variable. And in the example above, we consider the same employeeId's as the objects being equal. however maybe that's not enough. we could do this as well:

public class Employee {
  ...
  public boolean equals(Object o){
    if(o == null)                return false;
    if(!(o instanceof) Employee) return false;

    Employee other = (Employee) o;
    if(this.employeeId != other.employeeId)      return false;
    if(! this.firstName.equals(other.firstName)) return false;
    if(! this.lastName.equals(other.lastName))   return false;

    return true;
  }
}

Here, the employee id's, , first name, and last name must ALL be the same in order for the two objects to be equal. I struggled with this at first as well but now i can see how it gives more flexibility and lets us customize what our equal method actually does!

I hope this helped. cheers!

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hi Kevin,

thank you for this great answer but to be honest ... I still donΒ΄t understand this topic at all :)

So I try to stay tuned here:

"remember before that if we tried to call an object as a string"

Is this like doing:

public class UnderstandingToStringMethod{

public String returnObect(Object o){
   return o;
}
//So we have to define the method toString() to prevent errors in the returnObject method ???

@Override
public toString(Object o){
whrite that o is a String and not an Object????
}

Thanks for patience