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

7.3 Object and equals — the class everything inherits

Lesson

Все классы — наследники Object

Even a class that extends nothing has a superclass: Object, the root of every hierarchy in Java. That is where toString and equals come from — every object has them, whether you wrote them or not.


Что они делают по умолчанию

class Plain { int v; }

Plain p1 = new Plain();
System.out.println(p1);           // Plain@6d06d69c  — the class name and an address
System.out.println(p1.equals(p2)); // false, even with identical contents

Both are technically correct but practically useless. The default toString prints an address instead of the contents, and the default equals compares references — exactly what == does, no more.

So they are not there to be used as-is; they are there to be overridden. You already overrode toString in module 4. The next lesson does equals.


▶ Try it: run this, then change something and run it again.



A class that extends nothing still inherits from...


The default equals compares...


Type exactly what this program prints.

class Box {
    int size;

    Box(int size) {
        this.size = size;
    }
}

public class Main { public static void main(String[] a){
    Box x = new Box(3);
    Box y = new Box(3);
    System.out.println(x.equals(y));
    System.out.println(x.equals(x));
}}

Why is the default toString rarely useful?


True or false?