Scala中访问控制与方法重写(二)

40 阅读1分钟

重写equal方法

重写equals方法的语法格式:

override def equals(obj: Any): Boolean = {

     true/false  
if (obj == null || obj.getClass != this.getClass) return false

    // 类型转换和字段比较

    val other = obj.asInstanceOf[Student]

    (this.ID == other.ID) && (this.name == other.name)

}

判断两个对象是相等的?

两个对象做比较==时,会自动调用equals方法。我们可以重写equals方法,并自己定义两个对象相等的标准。

object class04 {
  class Student(var name:String,var id:String,var age:Int) {
    // equals 相等
    override def equals(obj: Any): Boolean = {
      println("调用了equals..")

      println(this, obj)
      // 判断this和obj是否相等的逻辑: 姓名和学号都相等,说明这两个学生是同一个人
      val other = obj.asInstanceOf[Student]

      this.name == other.name && this.id == other.id
    }
  }

  def main(args: Array[String]): Unit = {

    val stu1 = new Student("小花", "20230012", 18)
    val stu2 = new Student("小花", "20230012", 18)
    val stu3 = new Student("小花", "20230013", 18)
    // 目标,判断他们是一个人。使用 == 来输出的时候,应该要是true
    println(stu1 == stu2)  // true
    println(stu1 == stu3)  // false
  }
}