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

nazim khan
nazim khan
1,409 Points

How the toString method will run without calling from the Outer class

As shown in the Video How the toString() method ran without even calling it

2 Answers

Hello

Please review this

http://www.javatpoint.com/understanding-toString()-method

but in a nutshell, the toString method is a built in method that get called when you ask for a string representation of the object you created. Therefore, by saying something like this

pseudo code

...print(myObject)

the toString method built in myObject gets called and the string representation of myObject is rendered. You may override how the toString method renders your string representation of yourObject ... this is what the video did.

Alright, you need to look into inheritance.

So let's look at inheritance. Inheritance is when one class inherits the public methods and fields from another super class.

When ever you create a class in Java, in inherits all the public methods and fields from the Object class which you can know more about, here.

The Object super class, has a public method named toString() which returns the string representation of the class(basically, it is sort of an ID) which is as put by Javadoc,

A string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object.

It's totally fine if you don't understand all of that at the moment. All you need to know, is the following: Using the @Override annotation you can change the functionality of a method from a super class and then call that method normally, just like you would call a normal method. Using this, you can tell the toString() to output whatever you want it to output for you. For example: You could override the toString() to give you vital information about the class and its workings, etc. There are endless options.

Hope I could help you understand the concept :)