Implement the equals method - Java Object Oriented Design

Java examples for Object Oriented Design:equals method

Description

Implement the equals method

Demo Code

class Employee {//from  w  ww.  j  a v a2s  .c om
  private String name = "Unknown";

  public void setName(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }

  public boolean equals(Object obj) {
    boolean isEqual = false;

    // We compare objects of the Employee class with the objects of
    // Employee class or its descendants
    if (obj instanceof Employee) {
      // If two have the same name, consider them equal.
      Employee e = (Employee) obj;
      String n = e.getName();
      isEqual = n.equals(this.name);
    }

    return isEqual;
  }
}

class Manager extends Employee {
  // No code is needed for now
}

public class Main {
  public static void main(String[] args) {
    Employee emp = new Employee();
    emp.setName("Edith");

    Manager mgr = new Manager();
    mgr.setName("Edith");

    System.out.println(mgr.equals(emp)); // prints true
    System.out.println(emp.equals(mgr)); // prints true
    System.out.println(emp.equals("Edith")); // prints false
  }
}

Result


Related Tutorials