Mark As Completed Discussion

Stringify Function

If you want to print your custom class to the console or make it a string to send to another object for some purpose, you'll most likely use a built-in class function named toString() in Java. Currently, the default toString() method returns the name of the class along with its package name as well as the hash code in hex format of the class calculated with another built-in method hashCode(). So if you were to print an object of type Rectangle, you would get something like this "shapes.Rectangle@abcdefgh" as output.

If you want to print something different, then - like other methods - you can override the toString() method and return whatever you want to print. For our example, we will print the name of the Rectangle with its package name and its area inside parentheses. All the built-in classes (Integer, Double, BigInteger, etc.) have overridden the toString() method to return a more informative string (the value instead of Class name and hash code).

TEXT/X-JAVA
1package shapes;
2
3// Rectangle.java
4public class Rectangle extends Shape {
5    protected int height;
6    protected int width;
7
8    @Override
9    public double getArea() {
10        return (double)height*width;
11    }
12
13    @Override
14    public String toString() {
15        return "shapes.Rectangle(area=" + this.getArea() + ")";
16    }
17}
18
19// Main.java
20public class Main {
21    public static void main(String[] args) {
22        Rectangle rect = new Rectangle();
23        rect.setHeight(5); rect.setWidth(4);
24        System.out.println(rect); // shapes.Rectangle(20)
25    }
26}