Casting in equals method

前端 未结 7 1398
攒了一身酷
攒了一身酷 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:29

    The properties name and age are specific only to Dog. You can't access name or age by using obj, which is an Object. For ex, the following code will generate compile time error:

    this.name.equals(obj.name)
    

    I don't understand why why have to cast the reference to the Dog reference. If that reference is not of type Dog we return false. Why all the hassle with casting it ?

    Because although the reference is of Dog it doesn't means that it is the same Dog. The name of the other dog may not be the same as your Dog. In order to compare the name and age of the other Dog with your Dog, it has to be cast first.

    0 讨论(0)
提交回复
热议问题