0

I am new to java, and i was wondering what is the difference between equales and ==, i know you can over ride equales, and you can't overrdie ==, but how?

Lets say i have java class Dogs, and if dogs are from same kind i want them to be equale, how can i do it?

    public class Dogs{
        private String dogKind;

        public Dogs(String kind){
            this.dogKind = kind
        }

        public String getDogKind(){
            return this.dogKind;
        }
     }

So where in how i override equales?

1 Answers1

0

Just simply read online(So many good answers), and if you dont understand:

You need to add this in the Dogs class, simply do:

    @Override
    public boolean equals(Object obj) {
        if (!obj instanceof Dogs){
            return false;
        }
        return this.dogKind.equals(((Dogs)obj).getDogKind());
    }

The first part makes sure that the object given to the method is not null or from a different class.

The second part simply uses String equals, to check if the Strings are the same or not.

Gigalala
  • 439
  • 1
  • 8
  • 24