1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
/* 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( "这句话是否执行?" ); // 如果异常得到了处理, 那么这句话就会执行,否则就不会被执行!
}
} |
本文转自 小眼儿 博客园博客,原文链接:http://www.cnblogs.com/hujunzheng/p/3871938.html,如需转载请自行联系原作者