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

Kamran Ismayilov
Kamran Ismayilov
5,753 Points

toString() method

I do not get what exactly this method " toString() " did? I tried to run the programm without it, and the programm still works the same as before.

Yes and what about Inheritance? I did not see it either

2 Answers

the toString() is a method originally defined by the Object class.

The Object class is the mother of all objects in java i.e every class in the java api extends the Object class.

some subclasses of the Object Class have overridden the toString() method to suit their own output.

user defined classes automatically extends the Object class but do not override the toString() method automatically.

You have to explicitly override the toString() when u define your own class.

e.g

// what u define public class ToStringTest {

  public ToStringTest () {
   }

}

// whats happening behind the scene public class ToStringTest extends Object {

  public ToStringTest () {
   }

}

so if u check your ToStringTest class toString() method in the java main() {}

e.g ToStringTest test = new ToStringTest();

System.out.println(test.toString());

// OUTPUT com.example.ToStringTest@2f0e140b

u will get an output of the package name . ClassName . and a unique object identifier -> @2f0e140b // note this identifier is not the same for all objects instantiated from the ToStringTestClass

to get a human readable text that suits your need, you need to explicitly override the toString() method in your class.

e.g { // somewhere inside your class @override public String toString () { return "overridden toString() method from the ToStringTest class"; }

HOPE THIS HELPS

toString really just converts a char to a String, as it is aptly named.