Click here to Skip to main content
15,886,067 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
public class Dog {
    private String name;

    public Dog(String name){
        this.name = name;
    }

    public boolean equals(Object other){
        Dog d1 = (Dog) other;
        return this.name.equals(d1.name);
    }

    public static void main(String[] args)
    {
        Dog d1 = new Dog("Rufus");
        Dog d2 = new Dog("Sally");
        Dog d3 = new Dog("Rufus");
        Dog d4 = d3;
        System.out.println(d1.equals(d2));
        System.out.println(d2.equals(d3));
        System.out.println(d1.equals(d3));
        System.out.println(d3.equals(d4));
    }
}


What I have tried:

I have tried to think about it for a long and searched but in vain, I'm a beginner in oop in java
Posted
Updated 29-Apr-22 5:26am
Comments
0x01AA 29-Apr-22 11:23am    
equals does simply compare the name of the two instances and returns true if the names are equal and otherwhise false. It is not a big thing and looks like you are searching to far ;)

1 solution

Java
  1  Dog d1 = (Dog) other;
  2  return this.name.equals(d1.name);

Line 1 casts the passed object to a Dog type. If the object is not a Dog then this will cause an exception. Line 2 compares the name of the passed object, and the name of "this" to see if they are equal.

More information on classes can be found at Lesson: Classes and Objects (The Java™ Tutorials > Learning the Java Language)[^].
 
Share this answer
 
Comments
0x01AA 29-Apr-22 11:50am    
"Line 1 casts the passed object to a Dog type. If the object is not a Dog then this will cause an exception":
Does this really ends in an exception in line 1 and not let d1 undefined/null and the exception will happens in line 2?
Anyway a 5.
Richard MacCutchan 29-Apr-22 12:23pm    
Yes, it causes an exception at the cast:
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class Dog
0x01AA 29-Apr-22 12:26pm    
Thanks
CPallini 29-Apr-22 12:54pm    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900