Objectクラスでよく使われるメソッド
8124 ワード
hashCode:
getClass:
toString:
1 class Person{
2 private int age;
3 Person(int age){
4 this.age = age;
5 }
6
7 /*
8
9 public int hashCode{
10 return age;
11 }
12 */
13
14 public boolean equals(Object obj){
15 if(!(obj instanceof Person)){
16 throw new ClassCastException(" ");
17 }
18 Person p = (Person)obj;
19 return this.age == p.age;
20 }
21 }
22 class ObjectDemo {
23 public static void main(String[] args) {
24 Person p1 = new Person(20);
25 Person p2 = new Person(20);
26 Person p3 = p1;
27 System.out.println(p1.hashCode());// p1 5184781
28 System.out.println(Integer.toHexString(p1.hashCode()));// p1 4f1d0d
29 System.out.println(p1);// p1 com.wrapper.demo.Person@4f1d0d
30 }
31 }
getClass:
1 class Person{
2 private int age;
3 Person(int age){
4 this.age = age;
5 }
6 }
7 class ObjectDemo {
8 public static void main(String[] args) {
9 Person p1 = new Person(20);
10 Person p2 = new Person(20);
11 Person p3 = p1;
12 System.out.println(p1.getClass());//
13 }
14 }
toString:
1 class Person{
2 private int age;
3 Person(int age){
4 this.age = age;
5 }
6 // Object toString
7 public String toString(){
8 return "Person:"+age;
9 }
10 }
11 class ObjectDemo {
12 public static void main(String[] args) {
13 Person p1 = new Person(20);
14 Person p2 = new Person(20);
15 Person p3 = p1;
16 System.out.println(p1.toString());
17 }
18 }