You can structure your equals method similarly to an if statement. You just need to cast the other argument first before your can compare their fields.

@Override
public boolean equals(Object o) {
    // Check if the other object is also a Student
    if (o instanceof Student) {
        // Now that we know o is a student, we can safely cast it
        Student other = (Student) o;

        // Similarly to how you would write an if statement you can compare each individual field.
        // Thanks to inheritance, we defer the equality check of each field to its own implementation
        return this.firstName.equals(other.firstName)
            && this.lastName.equals(other.lastName)
            && this.birthDate.equals(other.birthDate);
    }

    // Other object was not a student
    return false;
}

You then need to go write something similar in Date so that when you compare birthDate, it will know what to do.

You can also take this one step farther by using Objects.equals(a, b) instead of a.equals(b). This will ensure you do not get a nullPointerException if a happens to be null when comparing them. However, since this looks to be a school project I imagine you may be expected to either check manually or assume the values will not be null instead of using the standard library.

Answer from Locke on Stack Overflow
Top answer
1 of 2
2

You can structure your equals method similarly to an if statement. You just need to cast the other argument first before your can compare their fields.

@Override
public boolean equals(Object o) {
    // Check if the other object is also a Student
    if (o instanceof Student) {
        // Now that we know o is a student, we can safely cast it
        Student other = (Student) o;

        // Similarly to how you would write an if statement you can compare each individual field.
        // Thanks to inheritance, we defer the equality check of each field to its own implementation
        return this.firstName.equals(other.firstName)
            && this.lastName.equals(other.lastName)
            && this.birthDate.equals(other.birthDate);
    }

    // Other object was not a student
    return false;
}

You then need to go write something similar in Date so that when you compare birthDate, it will know what to do.

You can also take this one step farther by using Objects.equals(a, b) instead of a.equals(b). This will ensure you do not get a nullPointerException if a happens to be null when comparing them. However, since this looks to be a school project I imagine you may be expected to either check manually or assume the values will not be null instead of using the standard library.

2 of 2
0

For equals to work, you need to override hashCode also. Further equality check needs actual comparison of your objects.

Also, any related objects also has to implement hashCode and equals method. In this case Date.

Possible code

import java.util.Objects;

class Date {

    public int day;
    public int month;
    public int year;

    public Date(int d, int m, int y) {
        this.day = d;
        this.month = m;
        this.year = y;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Date date = (Date) o;
        return day == date.day &&
            month == date.month &&
            year == date.year;
    }

    @Override
    public int hashCode() {
        return Objects.hash(day, month, year);
    }
}

public class Student {

    private final String firstName;
    private final String lastName;
    private Date birthDate;

    public Student(String firstName, String lastName, Date birthDate) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.birthDate = birthDate;
    }

    public static void main(String[] args) {
        System.out.println(new Student("John", "Johnny", new Date(10, 10, 10))
            .equals(new Student("John", "Johnny", new Date(10, 10, 10))));
        System.out.println(new Student("John", "Johnny", new Date(11, 10, 10))
            .equals(new Student("John", "Johnny", new Date(10, 10, 10))));
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Student student = (Student) o;
        return Objects.equals(firstName, student.firstName) &&
            Objects.equals(lastName, student.lastName) &&
            Objects.equals(birthDate, student.birthDate);
    }

    @Override
    public int hashCode() {
        return Objects.hash(firstName, lastName, birthDate);
    }
}
🌐
Baeldung
baeldung.com › home › java › core java › comparing objects in java
Comparing Objects in Java | Baeldung
October 10, 2025 - In this tutorial, we’ll explore some of the features of the Java language that allow us to compare objects. We’ll also look at such features in external libraries. Let’s begin with the == and != operators, which can tell if two Java objects are the same or not, respectively.
Discussions

How does Java "==" operator check equality between objects? Trying to understand how Object.equals() works
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
20
1
January 8, 2023
Comparing Java objects with different member variables - Software Engineering Stack Exchange
People and Student may then just use a different transformation that will be passed to the comparator; Or ... Java has two interfaces that can be used for sorting (Comparator and Comparable) the first compares two objects of the same type (T) the second can be implemented by a class to ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 8, 2023
How to compare two java objects - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Closed 12 years ago. I have two java objects that are instantiated from the same class. More on stackoverflow.com
🌐 stackoverflow.com
How to compare two Java objects?
By convention, each Java class has an equals method that is inherited from the base Object class. The actual implementation depends on the use case. In your example, you could check that the two objects have the same values for number, color and ball. More on reddit.com
🌐 r/javahelp
8
1
July 12, 2017
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-compare-two-objects
Java Program to Compare Two Objects - GeeksforGeeks
July 23, 2025 - Though the values of dog1 and dog2 are the same, equals() method always checks the reference of the two objects i.e if both the objects passed refer to the same object or not and not their values.
🌐
Medium
medium.com › @dr4wone › equals-vs-compareto-in-java-understanding-the-differences-fce0a0d4b292
Equals vs. compareTo in Java: Understanding the Differences | by Daniel Baumann | Medium
April 9, 2023 - The equals() method is used to compare objects for equality. It returns true if two objects are equal and false if they are not. By default, the equals() method in Java compares objects based on their memory location.
🌐
InfoWorld
infoworld.com › home › blogs › java challengers
Comparing Java objects with equals() and hashcode() | InfoWorld
May 16, 2024 - In the first comparison, equals() compares the current object instance with the object that was passed. If the two objects have the same values, equals() returns true. In the second comparison, equals() checks to see whether the passed object ...
Find elsewhere
Top answer
1 of 5
3

The “different member variables” is irrelevant. It’s an implementation detail. What you need is a set of rules which of two people comes first.

You could for example sort by family name, then given name, then date of birth, and if these are all three equal, take the name of the school, university or company (which will be different member variables) and compare them as strings. If that is equal, you might have student and employee ids, and the student ids might be unique, and the employee ids might be unique, but student and employee ids might be the same. So you could sort then students first ordered by id, followed by employees sorted by id, if you might sort by if first if student and employee ids are comparable.

(University or school and employer might be the same, because universities are also employers).

2 of 5
3

Comparing objects with different fields sounds like bad polymorphic design, whether it's Java or any other OOP language:

  • If your comparator needs to know the precise subtype of an object to do the comparison, you mess-up with the the open-closed principle, since for every new subclassing, you'd potentially need to modify the comparator to select the relevant fields.
  • If your comparator needs uses reflexion to find on its own the relevant fields to compare, you indirectly mess up with the principle of encapsulation, since you create a hidden requirement that information to be compared must be in some predetermined field.

If you want to sort People properly in a clean polymorphic design:

  • you need to rely either on a field, available for any kind of People, including Student, or
  • you may call some function/transformation that provides a unique value (e.g. a string) that allows to sort any People. People and Student may then just use a different transformation that will be passed to the comparator; Or
  • you only sort among homogeneous subtypes.
🌐
Runestone Academy
runestone.academy › ns › books › published › csjava › Unit3-If-Statements › topic-3-7-comparing-objects.html
3.7. Comparing Objects — CS Java
Only use == with primitive types like int or to test if two strings (or objects) refer to the same object. Use equals, not ==, with strings which will check to see if they are equal letter by letter. The one common place to use == or != with objects is to compare them to null to see if they ...
🌐
Medium
medium.com › @AlexanderObregon › javas-objects-compare-method-explained-7a9ccda5ea74
Java’s Objects.compare() Method Explained | Medium
December 13, 2024 - The Objects.compare() method in Java is a utility that simplifies the process of comparing two objects by utilizing a specified Comparator. It is particularly useful for handling scenarios where objects being compared may include null values. ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › compare-objects-by-multiple-fields-in-java
How to Compare Objects by Multiple Fields in Java? - GeeksforGeeks
July 23, 2025 - To compare objects by multiple fields in Java using a Custom Comparator, you can follow this approach, Suppose you have a class MyClass with fields field1, field2, and field3.
🌐
Msgprogramator
msgprogramator.sk › home › java › how to compare java objects correctly
Java Objects: How to Compare Them Correctly - msgprogramator.sk
July 7, 2025 - The equals() method is the primary method for comparing two objects in Java. When we override the equals() method, we must also override the hashcode() method to ensure that two identical objects have the same hash code.
🌐
W3Schools
w3schools.com › java › ref_string_compareto.asp
Java String compareTo() Method
Tip: Use the equals() method to compare two strings without consideration of Unicode values. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to ...
🌐
Java Programming
java-programming.mooc.fi › part-8 › 3-similarity-of-objects
Similarity of objects - Java Programming
The equals method checks by default whether the object given as a parameter has the same reference as the object it is being compared to. In other words, the default behaviour checks whether the two objects are the same. If the reference is the same, the method returns true, and false otherwise.
🌐
Mendix
community.mendix.com › link › space › java-actions › questions › 87391
Comparing two objects and showing the changed attributes
July 5, 2017 - The Mendix Forum is the place where you can connect with Makers like you, get answers to your questions and post ideas for our product managers.
🌐
Reddit
reddit.com › r/javahelp › how to compare two java objects?
r/javahelp on Reddit: How to compare two Java objects?
July 12, 2017 -

Hi there, it's my first time learning Java and I'd love some assistance with comparing two Java objects. Here is a KenoBall class:

public class KenoBall {

    private static int number;
    private static String colour;
    private static String ball;

    public KenoBall(int number, String colour) {
        this.number = number;
        this.colour = colour;
        this.ball = number + colour;
        System.out.print(number + colour + "\n");
    } 

    public boolean matches(KenoBall other) {
        if (What goes in here?) {
            System.out.println("Tru");
            return true;
        } else {
            System.out.println("False");
            return false;
        }
    } 

 }

And in my main method:

    public static void main(String[] args) {
        KenoBall k1 = new KenoBall(1, "R");
        KenoBall k2 = new KenoBall(1, "R");
        KenoBall k3 = new KenoBall(4, "B");
    
        k1.matches(k2);
    }

If anyone can point me in the right direction I'd really appreciate it! Basically I'm trying to see if k1 is equal to k2 (and it should).

Thank you!

🌐
TutorialsPoint
tutorialspoint.com › java-program-to-compare-two-objects
Java Program to Compare Two Objects
To compare objects in Java, check the properties or the hash value of given objects. If the properties of both objects matches, then they are equal. If either property is different, it indicate that the objects are not equal.
🌐
Quora
quora.com › How-can-two-lists-of-objects-be-compared-in-Java
How can two lists of objects be compared in Java? - Quora
Java (programming languag... ... Comparing two lists of objects in Java depends on what “compare” means in your context: equality (same elements, order matters or not), ordering (which list is greater), or set-like differences (which elements added/removed).
🌐
Baeldung
baeldung.com › home › java › using the apache commons lang 3 for comparing objects in java
Using the Apache Commons Lang 3 for Comparing Objects in Java | Baeldung
January 8, 2024 - Here, we use the DiffBuilder to implement the compare() method. When generating the DiffBuilder using the append() methods, we can control exactly which fields will be used in the comparison.