Start learning free

LESSON 607 OF 635 · OBJECT-ORIENTED PROGRAMMING

Printing Objects in Java in Java

Lesson

TL ; DR:

Override toString to return a string. Then System.out.println shows that string for the object.


class Cat {
    public String name;

    public Cat(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Cat named " + name;
    }
}

// System.out.println(new Cat("Tom")) prints Cat named Tom


Full lesson:

Every Java class inherits a toString method from Object. Java calls it to turn an object into text. The inherited one only knows the class name and a hash code:

Cat@1b6d3586

That tells you nothing about the cat.

So override toString, as you overrode methods before. Return the text that stands for the object.

Java calls it whenever the object becomes text. System.out.println(tom) does that. So does "I have " + tom.

toString is public, takes no parameters and returns a String. It must return the text, not print it.

@Override asks the compiler to check the name. A typo like tostring then becomes an error.


Your task

The Dog class below has a name and an age. Override toString in it.

It returns the name, then " is ", the age and " years old". The code in mainFunction prints two dogs.

Expected output:

Rex is 3 years old
Bella is 5 years old
STEP 1 OF 2
    Ctrl + Enter to check

    Printing Objects in Java

    Keep going with Java500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free