본문 바로가기
IT/Java

Object 클래스 정리

by 어센트 2019. 12. 31.

 

Object클래스는 모든 클래스의 최상위 클래스이다.

java.lang.Object 클래스

모든 클래스는  Object클래스에서 상속받는다.

모든 클래스는 Object클래스의 메서드를 사용할 수 있다.

모든 클래스는 Object클래스의 일부 메서드를 재정의 하여 사용가능하다.

 

1. toString()

 객체의 정보를 String 으로 바꾸어 사용할 때 유용함 자바클래스 중에는 이미 정의되어있는 클래스가 많다.(String,Integer,Calender 등) 많은 클래스에서 재정의하여 사용한다. 

 

2. equals()

  두 객체의 동일함을 논리적으로 재정의 할 수 있다.

 물리적 동일함: 같은 주소를 가지는 객체

 논리적 동일함: 같은 학번의 학생,같은 주문 번호 등

 물리적으로 다른 메모리에 위치한 객체라도 논리적 동일함을 구현하기위해서 사용하기위한 메소드

 

3. hashCode()

 인스턴스가 저장된 가상머신의 주소를 10진수로 반환한다. 두개의 서로 다른 메모리에 위치한 인스턴스가 동일하다는 것은 논리적으로 동일하다는 것을 의미하며 equals()의 반환값이 true임을 의미한다. 즉 hashCode()의 반환값도 동일하도록 재정의 해주어야한다.

 

4. clone()

 객체의 복사본을 만드는 것으로  Prototype으로 부터 같은 속성 값을 가진 객체의 복사본을 생성할 수 있다. 객체지향 프로그래밍의 정보은닉에 위배되는 가능성이 있으므로 복제할 객체는 clonable인터페이스를 명시해야한다.

 

5.finalize()

 직접호출하여 사용하는 메소드가 아니라 인스턴스가 힙메모리에서 해제될 떄 garbage 콜렉터에서 호출되는 메서드이다.

 

 

예제 코드 1 

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
46
47
48
49
50
51
52
53
54
55
package object;
class Book implements Cloneable{ //복제가 가능하도록 Cloneable인터페이스 명시
    String title;
    String author;
    
    public Book(String title,String author) {
        this.title = title;
        this.author = author;
    }
 
    @Override
    public String toString() {
        return author + "," +title;
    }
 
    @Override
    protected Object clone() throws CloneNotSupportedException {
        
        return super.clone();
    }
 
    @Override
    protected void finalize() throws Throwable {
         //직접 호출하는 매소드가 아니라 인스턴스가 힙메모리에서 해제될때 가비지 콜렉터에서 호출되는 메서드
        
        super.finalize();
    }
    
    
}
public class ToStringTest {
 
    public static void main(String[] args) throws CloneNotSupportedException {
    
        Book book = new Book("토지""박경리");
        
        System.out.println(book);
        //toString을 재정의 해줬기 때문에 토지,박경리가 출력된다.
        
        String str = new String("토지");
        System.out.println(str);
        
        //String의 경우 str.toString() 이 호출됨
        //toString 매소드는 어떤 객체의 정보를 스트링 형태로 표현해야할때 추출되는 메소드
        
        Book book2 = (Book)book.clone(); // clone 리턴타입이 Object이므로 다운캐스팅
        System.out.println(book2);
        
        
    }
    //Object클래스는 모든 클래스의 최상위 클래스이다.
    
 
}
 
cs

 

 예제코드2

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package object;
 
class Student{
    int studentNum;
    String studentName;
    
    public Student(int studentNum,String studentName) {
        this.studentNum = studentNum;
        this.studentName = studentName;
    }
 
    @Override
    public boolean equals(Object obj) {
        if(obj instanceof Student) { // obj가 Studnet 인스턴스인지 확인
            
            Student std = (Student)obj;//업캐스팅되서 들어온것을 다운 캐스팅해줌
            return(this.studentNum == std.studentNum); //학번이 같으면 같은 학생으로 인정
        }
        return false;
        
    }
 
    @Override
    public int hashCode() { //equals를 오버라이딩할때 일반적으로 해쉬코드도 오버라이딩해준다.
        
        return studentNum;
    }
    
}
public class EqualsTest {
 
    public static void main(String[] args) {
 
        String str1 = new String("abc");
        String str2 = new String("abc");
        
        System.out.println(str1 == str2);
        //주소가 다름
        System.out.println(str1.equals(str2));
        //abc abc로 동일
        
        Student Lee = new Student(100,"이범수");
        Student Lee2 = Lee;
        Student soo = new Student (100,"이범수");
        
        System.out.println(Lee == Lee2); // true
        System.out.println(Lee == soo); // false;
        System.out.println(Lee.equals(soo));//이 경우 논리적으로 학번이 같기 때문에 true로 반영하고싶다
        //따라서 equals를 재정의 해서사용한다 재정의 해주기 전까지는  false로 출력된다
        
//        System.out.println(Lee.hashCode());
//        System.out.println(Lee2.hashCode());
        
        Integer i1 = new Integer(100);
        Integer i2 = new Integer(100);
        
        System.out.println(i1.equals(i2)); 
        // 두개의 객체의 equals가 true라면 hashcode도 동일
        
        //실제 메모리주소를 알려면??
        System.out.println(System.identityHashCode(i1));  //을 통해 실제 메모리주소를 알아본다.
        System.out.println(System.identityHashCode(i2));   //실제 두 변수의 메모리 주소는 다르다.
        
        
    }
 
}
 
cs

 

예제 코드3 날짜비교 Object클래스를 활용하여 비교해보기

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
46
47
48
49
50
51
52
53
54
55
56
package coding;
 
class MyDate{
    int day;
    int month;
    int year;
    
    public MyDate(int day,int month,int year) {
        this.day = day;
        this.month = month;
        this.year = year;
    }
 
    @Override
    public boolean equals(Object obj) {
        if(obj instanceof MyDate) {
            
            MyDate date = (MyDate)obj;
            return date.day == this.day 
                    && date.month == this.month && date.year == this.year;
            
        }
        return false;
        
    }
 
    @Override
    public int hashCode() {
        String hashStr = Integer.toString(year)+Integer.toString(month)+Integer.toString(day);
        
        return Integer.parseInt(hashStr);
    }
 
    @Override
    public String toString() {
        
        return Integer.toString(year)+"년"+Integer.toString(month)+"월"+Integer.toString(day)+"일";
    }
}
public class MyDateTest {
 
    public static void main(String[] args) {
        
        MyDate date1 = new MyDate(10122020);
        MyDate date2 = new MyDate(10122020);
        
        
        System.out.println(date1.equals(date2));
        System.out.println(date1.hashCode());
        System.out.println(date2.hashCode());
        System.out.println(date1);
    
    }
 
}
 
cs