Object Class Methods

Every Class Extends Object

Every Java class automatically extends java.lang.Object. So every object has these methods:

MethodDefault behaviourUsually override?
toString()class name + @ + hash, e.g. Product@1b6d3586yes, for readable logs
equals(Object o)true only for the same object (like ==)yes, to compare by value
hashCode()number based on identityyes, whenever you override equals
getClass()runtime class of the objectno (final)

Overriding toString and equals

Example

Two products with the same id are equal by value after we override equals. The == operator still compares references.

import java.util.Objects;

public class Main {
    public static void main(String[] args) {
        Product a = new Product(101, "Phone");
        Product b = new Product(101, "Phone");
        System.out.println(a);
        System.out.println("a == b      : " + (a == b));
        System.out.println("a.equals(b) : " + a.equals(b));
        System.out.println("same hash   : " + (a.hashCode() == b.hashCode()));
        System.out.println("class       : " + a.getClass().getSimpleName());
    }
}

class Product {
    int id;
    String name;

    Product(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public String toString() {
        return "Product{id=" + id + ", name=" + name + "}";
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Product)) return false;
        Product other = (Product) o;
        return id == other.id && name.equals(other.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
}

Output

Product{id=101, name=Phone}
a == b      : false
a.equals(b) : true
same hash   : true
class       : Product

Tip: The full equals/hashCode contract and immutable classes are covered in the Advanced level. For now: if you override equals, always override hashCode too.