Object类

Object类是其他所有类的爹

需求:复写Object类的public boolean equals(Object obj)方法

 1 /**
 2 *需求:复写Object的public boolean equals(Object obj)方法
 3 *功能:比较Person的num值与另一个对象的num值是否相等
 4 */
 5 class Person
 6 {
 7     private int num;
 8     //构造方法
 9     Person(int num){
10         this.num=num;
11     }
12     //复写equals
13     public boolean equals(Object obj){
14         /*这样写会报错,因为obj类没有定义num这个属性,需要下转型
15         return this.num==obj.num;
16         */
17         
18         /*弊端:当传入的参数不是Person对象时,不能强转型,所以需要判断处理
19         Person p=(Person)obj;
20         return this.num==p.num;
21         */
22         //如果不是相同对象,直接false
23         if(!(obj instanceof Person)) return false;
24         //强制下转型
25         Person p=(Person)obj;
26         return this.num==p.num;
27 
28     }
29 }
30 
31 class Dog
32 {
33 }
34 class Equals_obj 
35 {
36     public static void main(String[] args) 
37     {
38         Person p1=new Person(1);
39         Person p2=new Person(1);
40         Dog d=new Dog();
41         System.out.println(p1.equals(p2));
42         System.out.println(p1.equals(d));
43     }
44 }

 

posted @ 2015-07-31 17:11  洱海  阅读(200)  评论(0编辑  收藏  举报
.First { margin: 10px 0; font-family: 'Microsoft Yahei'; text-align: left; padding: 6px 20px; color: #fff; background: #55895B; font-size: 20px; border-radius: 4px; clear: both; } .Second { margin: 10px 0; font-family: 'Microsoft Yahei'; padding: 6px 20px; background: #93C8A2; color: white; font-size: 18px; border-radius: 4px; clear: both; } .Third { margin: 10px 0; padding: 6px 20px; font-family: 'Microsoft Yahei'; margin: 15px 0; font-size: 16px; color: black; background: #C6EFD2; border-radius: 4px; clear: both; } .note { margin: 10px 0; padding: 15px 20px 15px 60px; background: #FCFAA9 url('http://images.cnblogs.com/cnblogs_com/libaoheng/305804/o_yellow-pin.png') no-repeat 20px 0; font-size: 15px; font-family: 'Microsoft Yahei'; box-shadow: 0 0 8px #aaa; clear: both; } .demo { text-align: left; padding: 6px 20px; overflow: auto; border-radius: 4px; background: orange; color: #fff; font-size: 16px; clear: both; } .cnblogs_Highlighter { border: solid 1px #ccc; clear: both; } .cnblogs_code { background: #EFFFF4; border: solid 0px #939393; font-size: 14px; clear: both; padding: 10px 20px; } .cnblogs_code pre { font-size: 14px; } .cnblogs_code span { font-family: Courier New; font-size: 14px; }