Objects are not inherently printable.
If you try to print an object, you may get a representation of a reference to the object.
To print an object as an argument to
System.out.println(.... the object ....);
the compiler looks for a special method called
toString()
If this method is defined, it will be used to give a String representation of the object, which can then be printed.
The String representation can be defined to the programmer's liking.
For example, if we wanted our pair object to print in the form:
(7, 11)
where the numerals are the values of the x and y variables, we could define toString thus:
public String toString(){return "(" + x + ", " + y + ")";}
Next Slide | Previous Slide | Contents |