Jtest logo




Contents  Previous  Next  Index

PB.EQL


Use 'getClass()' in 'equals()' method implementation

Description

This rule flags code where an `equals()' method does not use 'getClass()' in the implementation.

Allowing only objects of the same class to be considered equal is a clean and simple solution to implementing the 'equals()' method correctly. The 'getClass()' method returns the runtime class of an object.Therefore, 'getClass()' can be used to implement the 'equals()' method for the object.

Example

 package PB;
 
 public class EQL {
     public boolean equals (Object o) {
         super.equals(o);     // violation
     }
 }

Repair

Use the `getClass()' method before comparing two objects' equality.

     public boolean equal (Object o) {
         if (getClass() != o.getClass()) 
             return false;
         // ...
     }

Reference

Haggar, Peter. Practical Java - Programming Language Guide. Addison Wesley, 2000, pp. 44 -47.


Contents  Previous  Next  Index

ParaSoft logo
(888) 305-0041 info@parasoft.com Copyright © 1996-2001 ParaSoft