Casting in equals method

前端 未结 7 1421
攒了一身酷
攒了一身酷 2020-12-31 09:46

I have a question about overriding the equals method in Java. In my book, I have the following example:

public class Dog{
     private String na         


        
7条回答
  •  孤独总比滥情好
    2020-12-31 10:23

    Because you are defining your own parameters for equality, you have to make sure they are the same class. That is, unless you're comparing them the == way, then you need to compare some value inside the objects. To compare values inside the objects, they need to be the same type!

    For example, let's say you have two Dogs.

    Dog dog1 = new Dog("Fido");
    Dog dog2 = new Dog("Rover");
    

    If you want to test if they have the same name, as I'm sure you know, you can't use:

    if(dog1 == dog2)
    

    So you override the equals method. However, because you're overriding it, it has to have the same method signature. A method signature is defined by the name of the method, and the number and type of it's parameters. Which means if you wish to override it, it needs to have a parameter of type Object. Hence:

    if(dog1.equals(dog2))
    

    The reason you need to cast it to use whatever method you're using to get the name value from the dog, and compare those values.

    A note on your class design

    The convention in object oriented programming, and certainly in Java, is to have Accessor and Mutator methods to get and change variables in a class. That is:

    dog1.name; ----> dog1.getName();
    

    where getName() looks like:

    public String getName()
    {
        return name;
    }
    

提交回复
热议问题