Chinaunix首页 | 论坛 | 博客
  • 博客访问: 686304
  • 博文数量: 152
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1793
  • 用 户 组: 普通用户
  • 注册时间: 2013-09-12 12:26
个人简介

相信自己,只有不想做的,没有做不到的。

文章分类

全部博文(152)

文章存档

2021年(1)

2015年(2)

2014年(74)

2013年(75)

分类: Java

2014-08-10 22:18:25

目标:掌握通过覆盖equals()方法的方式,来定义自定义对象相等的含义

源文件:CellPhone.java
package cn.com.CellPhone;

public class CellPhone {

//PIN 码
String pin;
public CellPhone(String pin){
this.pin = pin;
}


public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CellPhone other = (CellPhone) obj;
if (pin == null) {
if (other.pin != null)
return false;
} else if (!pin.equals(other.pin))
return false;
return true;
}
}

源文件:TestCellPhone.java
package cn.com.CellPhone;


public class TestCellPhine {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub


CellPhone c1 = new CellPhone("id100002");
CellPhone c2 = new CellPhone("id100002");

System.out.println(c1.pin.equals(c2.pin));
}


}

因为他们的身份证号相同。equals()方法因此将返回true,编译结果为:true

在这边,两个CellPhone 的对象相等的含义就是:它们有相同的pin。
阅读(369) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~