Sobes.tech
Junior — Middle

How is the comparison of instances of regular classes implemented in object-oriented programming?

sobes.tech AI

Answer from AI

In object-oriented programming, comparing instances of regular classes is usually done using the equals() method (in Java/Android) or by overriding the equals() and hashCode() methods.

By default, the equals() method compares object references (i.e., checks if variables point to the same object in memory). To compare the contents of objects, you need to override this method.

Example of overriding equals() in a class:

public class Person {
    private String name;
    private int age;

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Person person = (Person) obj;
        return age == person.age && name.equals(person.name);
    }

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

Thus, comparing class instances depends on the implementation of the equals() method, and without overriding, references are compared, not the content.

How is the comparison of instances of regular classes… - sobes.tech