Task 5 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

7.2 Overriding — the toString method

Lesson

Making an object printable

Every object has a toString() method (inherited from Object) that println uses to turn it into text. By default it returns something unhelpful — the class name and a hash code. Override toString() to return a readable description, and System.out.println(obj) will use it automatically.


Worked example

class Dog extends Animal {
    @Override
    public String toString() {
        return "Dog(" + getName() + ")";
    }
}

Dog d = new Dog("Rex");
System.out.println(d);   // "Dog(Rex)" — println calls toString()

You do not call toString() yourself; println calls it for you.


▶ Try it: run this — printing the Dog object uses your toString().



Which method does println use to turn an object into text?


By default (not overridden), toString() returns...


Type exactly what this program prints.

class Animal { String n; Animal(String x){n=x;} String getName(){return n;} }
class Dog extends Animal { Dog(String x){super(x);} public String toString(){return "Dog("+getName()+")";} }
public class Main { public static void main(String[] a){
    System.out.println(new Dog("Rex"));
}}

System.out.println(myDog) with an overridden toString() prints...


True or false?