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 Getting There Object Inheritance

Method does the same thing in the same amount of steps and why override the return statement?

I have two questions, the first is to do with overriding. Surely, we can just make a new method that does the same thing in the same amount of steps? Like so:

  @Override
  public String toString(){
    return "Treet:  \"" + mDescription + "\" - @" + mAuthor;
  }

  public String toStringTwo(){
    return "Treet:  \"" + mDescription + "\" - @" + mAuthor;
  }

The second question is, what is the overriding actually doing. If we are overriding the return statement of toString() then surely the rest of the code in that method doesn't matter?

I feel that i'm missing something here because everyone else seems to be fine with it. Thanks!

Eric Chan
Eric Chan
4,254 Points

thanks for asking! I am not one of those who you think are fine with the idea of overriding :) but now all clear

2 Answers

Zuhayr Elahi
Zuhayr Elahi
2,582 Points

So the @Override flag tells users that this method exists in the parent class, but we want to use this implementation of the method instead.

So if you want to know more about it, you can read about it here: https://docs.oracle.com/javase/tutorial/java/IandI/override.html

Now lets look at why its preferred to Override the toString() method, instead of writing a new function such as .toStringTwo(). Say I am using this class you created. How would I as a user know that there is a .toStringTwo() method? The only way is if you document it and tell me. I basically have to look at the documentation and find this special toStringTwo() method.

Now using the override function and overriding the .toString() of the parent class would help me and prevent me from having to read through and use a common method which is present in the base Object class from which all java classes are present.

Basically it abstracts the information away from whoever is using this .toString method and allows me to get the same functionality I would want from the toString function without having to look up how all the methods are implemented and then deciding what to use.

I hope this helps. If I am not clear or you want more information please feel free to reach out =)

Thanks for your help! That cleared everything up :)