您的位置:首页 > 移动开发 > Objective-C

java中Object.equals()简单用法

2014-07-27 21:14 483 查看
/*
equals()方法默认的比较两个对象的引用!
*/
class Child {
int num;
public Child(int x){
num = x;
}

//人文的抛出运行时异常的好处是:可以自定义错误信息!

/*public boolean equals(Object o) throws ClassCastException{
if(!(o instanceof Child)) throw new ClassCastException("中文提示:类型错误");
Child ch = (Child) o;
return num == ch.num ;
}*/

/*
Exception in thread "main" java.lang.ClassCastException: 中文提示:类型错误
at Child.equals(PC.java:8)
at PC.main(PC.java:17)
*/

public boolean equals(Object o){
Child ch = (Child) o;
return num == ch.num ;
}

/*
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot
be cast to Child
at Child.equals(PC.java:14)
at PC.main(PC.java:22)
*/
}

public class PC{
public static void main(String[] args){
Child p1 = new Child(11);
if(p1.equals(new Integer(11)))
System.out.println("true");

System.out.println("这句话是否执行?");// 如果异常得到了处理, 那么这句话就会执行,否则就不会被执行!
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: