DEV Community

Cover image for The Object Class and Its toString() Method
Paul Ngugi
Paul Ngugi

Posted on

The Object Class and Its toString() Method

Every class in Java is descended from the java.lang.Object class. If no inheritance is specified when a class is defined, the superclass of the class is Object by default. For example, the following two class definitions are the same:

Image description

Classes such as String, StringBuilder, Loan, and GeometricObject are implicitly subclasses of Object (as are all the main classes you have seen in previous posts so far). It is important to be familiar with the methods provided by the Object class so that you can use them in your classes. This section introduces the toString method in the Object class.

The signature of the toString() method is:

public String toString()

Invoking toString() on an object returns a string that describes the object. By default, it returns a string consisting of a class name of which the object is an instance, an at sign (@), and the object’s memory address in hexadecimal. For example, consider the following code for the Loan class defined in Loan.java, here:

Loan loan = new Loan();
System.out.println(loan.toString());

The output for this code displays something like Loan@15037e5. This message is not very helpful or informative. Usually you should override the toString method so that it returns a descriptive string representation of the object. For example, the toString method in the
Object class was overridden in the GeometricObject class in lines 46–48 in SimpleGeometricObject.java, in here as follows:

public String toString() {
return "created on " + dateCreated + "\ncolor: " + color +
" and filled: " + filled;
 }
Enter fullscreen mode Exit fullscreen mode

You can also pass an object to invoke System.out.println(object) or
System.out.print(object). This is equivalent to invoking System.out
.println(object.toString())
or System.out.print(object.toString()). Thus, you could replace System.out.println(loan.toString()) with System.out.println(loan).

Top comments (0)