Unit 2 (Prog 3) : Test equals() method.

By | June 2, 2013

Testing of equals() method and overriding equals() method of Object class.

// Overriding equals() method will make an object identical
// to use a object as a key, one has to override equals() method of Object class
 
public class EqualsTest {
          public static void main(String[] args) {
                    TestClass one = new TestClass(8);
                    TestClass two = new TestClass(8);
                    if (one.equals(two)) {
                              System.out.println(“one and two are equal”);
                   }
          }
}
class TestClass {
          private int testValue;
          TestClass(int val) {
                    testValue = val;
          }
          public int getTestValue() {
                    return testValue;
          }
//overriding equals() method of Object class
         public boolean equals(Object o) {
                   if ((o instanceof TestClass) && (((TestClass) o).getTestValue() == this.testValue)) {
                             return true;
                  } else {
                             return false;
                  }
         }
}
/* 
 * equals method is public in java.lang.Object class. 
 * while overriding the equals() method it must be declared as public. 
 * visibility can not be reduced in overriding a method. 
 */
email

Leave a Reply

Your email address will not be published. Required fields are marked *