1. Object 개요
1-1. Object란?
💡 자바에서 Object는 최상위 부모 클래스이다. Object 클래스에는 다양한 메소드로 구성되어 있다.
모든 클래스는 Object 클래스를 상속하고 있으므로 Object 안에 있는 메소드를 사용할 수 있다.
또한 Object 클래스가 가지는 메소드를 오버라이딩해서 사용하는 것도 가능하다.
1-2. Object 주요 메소드
동일하냐? 동등하냐?
메소드 |
설명 |
boolean equals(Object obj) |
전달 받은 객체와 같은지 여부를 반환 (동일하면 true, 다르면 false) |
int hashCode() |
객체의 해시 코드를 반환 |
String toString() |
객체의 정보를 문자열로 반환 |
2. Object 활용
2-1. toString()
- 인스턴스의 정보를 문자열로 반환
- 반환되는 문자열은 클래스 이름과 구분자 '@'를 사용, 그 뒤로 16진수 해시코드가 붙는다. (해시코드는 인스턴스 주소)
ex) 클래스명@16진수해시코드
- 해시코드가 아닌 인스턴스 안에 값을 확인하고 싶다면 오버라이딩(재정의)를 하면 된다.
2-2. equals()
- 매개변수로 전달받은 인스턴스와 == 연산해서 true, false로 반환. 즉, 동일한 인스턴스인지 비교하는 기능
- 동일 객체와 동등 객체
- 동일 객체 : 주소가 동일한 인스턴스를 동일 객체라고 한다.
- 동등 객체 : 주소는 다르더라도 필드값이 동일한 객체를 동등 객체라고 한다.
- 경우에 따라서는 동등 객체를 동일 객체로 취급해서 비교하고 싶은 경우가 발생. 즉, 동일한 필드값을 가지는 객체를 같은 객체로 판단할 수 있도록 하는 경우를 말한다. 그러한 경우 equals() 메소드를 오버라이딩하여, 각각의 필드가 동일한 값을 가지는지를 확인하고 모든 필드값이 같은 값을 가지는 경우 true, 아닌 경우 false를 반환하도록 작성
2-3. hashCode()
- 객체를 식별하는 값. Object의 hashCode() 메소드는 객체의 메모리 주소값을 이용해 해시코드를 만들어서 반환
- Object 클래스의 명세에 작성된 일반 규약에 따르면 equals() 메소드를 재정의 하는 경우 반드시 hashCode() 메소드도 재정의 하도록 되어있다.
- 만약 hashCode()를 재정의 하지 않으면 같은 값을 가지는 동등 객체는 같은 해시코드 값을 가져야 한다는 규약에 위반되게 된다.
(강제성은 없지만 규약대로 작성하는 것이 좋다.)
RUN
package com.ohgiraffers.section01.object.run;
import com.ohgiraffers.section01.object.dto.BookDTO;
public class Application1 {
public static void main(String[] args) {
BookDTO book1 = new BookDTO(1, "홍길동전", "허균", 50000);
BookDTO book2 = new BookDTO(2, "목민심서", "정약용", 30000);
Object book3 = new BookDTO(3, "칭찬은 고래도 춤추게 한다.", "고래", 10000);
System.out.println(book1.toString());
System.out.println(book2);
System.out.println(book3.toString());
}
}
BookDTO{number=1, title='홍길동전', author='허균', price=50000}
BookDTO{number=2, title='목민심서', author='정약용', price=30000}
BookDTO{number=3, title='칭찬은 고래도 춤추게 한다.', author='고래', price=10000}
package com.ohgiraffers.section01.object.run;
import com.ohgiraffers.section01.object.dto.BookDTO;
public class Application2 {
public static void main(String[] args) {
BookDTO book1 = new BookDTO(1, "홍길동전", "허균", 50000);
BookDTO book2 = new BookDTO(2, "홍길동전", "허균", 50000);
System.out.println("두 인스턴스를 == 연산자로 비교: " + (book1 == book2));
System.out.println("두 인스턴스를 equals() 메소드로 비교: " + book1.equals(book2));
System.out.println("book1의 hashCode: " + book1.hashCode());
System.out.println("book2의 hashCode: " + book2.hashCode());
System.out.println(System.identityHashCode(book1));
System.out.println(System.identityHashCode(book2));
}
}
두 인스턴스를 == 연산자로 비교: false
두 인스턴스를 equals() 메소드로 비교: true
book1의 hashCode: -1619945939
book2의 hashCode: -1619945939
1984697014
205029188
DTO
package com.ohgiraffers.section01.object.dto;
import java.util.Objects;
public class BookDTO {
private int number;
private String title;
private String author;
private int price;
public BookDTO() {
}
public BookDTO(int number, String title, String author, int price) {
this.number = number;
this.title = title;
this.author = author;
this.price = price;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "BookDTO{" +
"number=" + number +
", title='" + title + '\'' +
", author='" + author + '\'' +
", price=" + price +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BookDTO bookDTO = (BookDTO) o;
return price == bookDTO.price && Objects.equals(title, bookDTO.title) && Objects.equals(author, bookDTO.author);
}
@Override
public int hashCode() {
return Objects.hash(title, author, price);
}
}