Methods inherited from the Object class

The problem with the Object class is that it is not properly documented in Salesforce documentation and it’s hard to find information about inherited methods. We can only get more…

The Object is a supertype for all:

standard objects custom objects primitive types collections classes

The problem with the Object class is that it is not properly documented in Salesforce documentation and it’s hard to find information about inherited methods. We can only get more details while reading Java documentation and assuming it will work in the same way.

The following methods are inherited from the Object class:

toString()

Returns a string representation of the object. You can override toString() method in your class.

apex
public class A {}

System.debug(new A().toString()); // A:[]

public class A {
    public override String toString() {
        return 'Hello toString()';
    }
}

System.debug(new A().toString()); // 'Hello toString()'

equals()

Indicates whether some other object is "equal to" this one.

apex
public class A {}
public class B {}

System.debug(new A().equals(new B())); // false
System.debug(new A().equals(new A())); // false
System.debug(new A().equals('Some String')); // false

You cannot override standard equals method like toString, but still, you can have one. It’s beneficial when you need to create Custom Types in Map Keys and Sets.

apex
public class A {
    public Boolean equals(Object objectToCompare) {
        return true;
    }
}

public class B {}

System.debug(new A().equals(new B())); // true
System.debug(new A().equals(new A())); // true
System.debug(new A().equals('Some String')); // true

hashCode()

Returns a hash code value for the object.

apex
public class A {}

System.debug(new A().hashCode()); // 2069582068
System.debug('Some String'.hashCode()); // 2147069117

You cannot override standard equals method like toString, but still, you can have one. It’s beneficial when you need to create Custom Types in Map Keys and Sets.

apex
public class A {
    public Integer hashCode() {
        return 1234;
    }
}

System.debug(new A().hashCode()); // 1234

clone()

Creates and returns a copy of this object.

apex
public class A {
    public override String toString() {
        return 'My A';
    }

    public Boolean equals(Object objectToCompare) {
        return true;
    }
}

A oldA = new A();
A clonedA = oldA.clone();

System.debug(oldA); // My A
System.debug(clonedA); // My A

System.debug(clonedA.equals(oldA)); // true

Text and code were extracted from the original slide. Plain-text version of the whole catalog