A Representation to Print - toString()#
It is useful to be able to print objects of any class directly with System.out.println()
. Whenever we make a data type, i.e. a class with attributes and no main
method, if we don’t set up a toString()
method, then printing an object gives a memory address. For example, if we run this code:
Square mirror = new Square(5);
System.out.println("mirror: " + mirror);
mirror: REPL.$JShell$12$Square@5b10d0c9
Depending on our computer and version of Java, we will get different outputs, however they will all reflect a memory address, hexadecimal included. Some versions might look a little nicer, for example, Square@4617c264
. This is still not desirable.
If we, instead, prefer to show the dimensions of the object when it is printed, then we can write a toString()
method for the class. This method must return a String
, and take no parameters. The method works on an instance of the class. Here is an example, inside of the class Rectangle
, we write:
@Override
public String toString(){
return getClass().getName() + " " + length + " X " + width;
}
Now our println
call will output something more useful than just the hexadecimal address, likely Square 5.0 X 5.0
in a regular Java environment:
mirror: REPL.$JShell$12C$Square 5.0 X 5.0
Practice Questions#
Write a
toString()
method for theCircle
class (see Chapter 2).Write a
toString
method for theRightTriangle
class (see Chapter 2).Write a
toString
method for theSquare
class (see Previous Section).