Every class should implement toString()
method defined by Object.
The toString()
method has this general form:
String toString()
To implement toString()
, return a String object with a human-readable string that describes an object of your class.
// Override toString() for Box class. class Box { double width;//www . j a v a2 s.c om double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } public String toString() { return "Dimensions are " + width + " by " + depth + " by " + height + "."; } } public class Main { public static void main(String args[]) { Box b = new Box(10, 12, 14); String s = "Box b: " + b; // concatenate Box object System.out.println(b); // convert Box to string System.out.println(s); } }