集册 Java实例教程 实施equals方法

实施equals方法

欢马劈雪     最近更新时间:2020-01-02 10:19:05

520
实施equals方法

class Employee {

  private String name = "Unknown";
  /*来自 
   时代Java公众号 - N o w J a  v a . c o m*/


  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) {
    /*来自 
     NowJava.com - 时代Java*/

      // 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(
展开阅读全文