overriding the equals method in java

Lesilauv :

"Let’s implement the equals method for a Stamp class. You need to override the equals method of the Object class. Now you have a slight problem. The Object class knows nothing about stamps, so it declares the otherObject parameter variable of the equals method to have the type Object. When overriding the method, you are not allowed to change the type of the parameter variable."

Here, it says that we are not allowed to change type of the parameter variable. However, when I use the below code, it gives me the correct result.

public class Stamps
{
  private String color;
  private int value;

  public Stamps(String color, int value)
  {
    this.color=color;
    this.value=value;
  }

    public boolean equals(Stamps other)
    {
       return color.equals(other.color)
            && value== other.value;
    }
}


public class Main
{
     public static void main(String[] args)
     {
          Stamps stamp1 = new Stamps("red",10);
          Stamps stamp2 = new Stamps("green",10);

        System.out.println(stamp1.equals(stamp2));       
     }
}

Here, I'm not overriding the equals() method inherited from Object class since parameter types are different. So, instead of using my code, shouldn't it use the one inherited from Object class ?

Andy Turner :

When you write a method invocation expression in Java, a complex set of rules is followed to determine which method will be invoked.

Basically, the compiler will search for the most specific method that it can find which matches the types of the parameters you are trying to pass in.

The important thing about these rules is that they make no special provision for methods in Object, or any other class. The methods in Object are treated exactly the same as any method you define yourself.

So, if you are trying to invoke an equals method on an instance of class Stamps, passing in a single instance of Stamps as a parameter, it will find your method:

boolean equals(Stamps other)

This is more specific than the one on Object:

boolean equals(Object other)

("More specific" is informally defined in the spec thus: any parameter you can pass to a "more specific" method can also be passed to a "less specific" method, but not vice versa).

so the Java compiler will choose to invoke the equals(Stamps) method.

However, if you were to change either the first or second (or both) declarations of the variables to be of Object type:

Object stamp1 = new Stamps("red",10);

then the equals(Stamps) method would not be invoked:

  • For Object stamp1, this would be because Java would search the Object type for matching methods. Since only equals(Object) exists on Object, this is the only possible on to invoke.
  • For Object stamp2, this would be because the parameter type of equals(Stamps) would not match, so the only possible method to invoke would be equals(Object).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147304&siteId=1