Java OCA OCP Practice Question 1444

Question

Which method can be inserted into this class to meet the contract of the equals() method?

You may assume that text is not null.


class Button { 
   private String text; 

   public int hashCode() { 
      return text.hashCode(); 
   } 
} 
A. //  w  w w. j a  v  a  2s.  c  om

    public boolean equals(Object o) { 
       if ( o == null ) return true; 
       if (! (o instanceof Button)) return false; 
       return text.equals(o.text); 
    } 

B.  public boolean equals(Object o) { 
       if ( o == null ) return true; 
       Button b = (Button) o; 
       return text.equals(b.text); 
    } 

C.  public boolean equals(Object o) { 
        if (! (o instanceof Button)) return false; 
        return text.equals(o.text); 

     } 

D.  public boolean equals(Object o) { 
        if (! (o instanceof Button)) return false; 
        Button b = (Button) o; 
        return text.equals(b.text); 

     } 


D.

Note

The variable o that equals() is called on isn't null, since we can't call instance methods on a null reference.

A null reference could be passed as a method parameter.

If a null is passed in, the method should return false since an object and a null are not equal.

Options A and B are incorrect because the first line of those methods should return false rather than true.

Option C is incorrect because the cast is missing.

The Object class does not have a text variable available.

Option D shows a properly implemented equals() method and is correct.




PreviousNext

Related