티스토리 뷰
📌 230804 Object 클래스의 다양한 메소드들
Object 클래스
모든 클래스의 최상위 클래스로, java.lang 패키지 안에 있다.
String, Integer, System 등이 포함되었으며, 모든 클래스는 위 클래스를 상속받는다.
개발자가 상속 표시를 안 해줘도 컴파일러가 자동으로 extends Object 를 추가한다.
toString() 메소드
객체의 정보를 String으로 바꾸어서 사용할 때 쓰인다. String이나 Integer 클래스는 이미 재정의되어있다.
equals 메소드
두 인스턴스의 주소값을 비교하여 true/false를 반환해주는 함수이다.
그렇지만 재정의하여 필요시에 논리적으로 동일함의 여부를 구현할 때 쓰인다.
예를 들어 같은 학번을 가진 객체들은 논리적으로 같은 객체임을 보이고 싶을 때 사용하면 된다.
hashcode 메소드
인스턴스의 저장 주소를 반환한다.
힙 메모리에 인스턴스가 저장된 방식이 hash 방식이기 때문에 hashcode 메소드이다.
재정의하여 사용할 수 있다.
clone 메소드
객체의 원본을 복제하는데 사용한다. 생성과정의 복잡한 과정을 반복하지 않고 복제가 가능하다.
clone() 메소드를 사용하면 객체의 정보가 동일한 또 다른 인스턴스가 생성되는 것으로, 객체 지향 프로그램에서 정보은닉, 객체보호의 관점에서 위배될 수 있다.
구현해야하는 메소드는 따로 없고, 해당 클래스에 Cloneable 인터페이스를 상속시켜줘야한다.
📝 사용 예제
Student.class
public class Student implements Cloneable {
private int stuId;
private String stuName;
public Student(int stuId, String stuName) {
this.stuId = stuId;
this.stuName = stuName;
}
@Override
public String toString() {
return "Student{" +
"stuId=" + stuId +
", stuName='" + stuName + '\'' +
'}';
}
@Override
public int hashCode() {
return stuId;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Student) {
Student std = (Student) obj;
if (this.stuId == std.stuId) return true;
}
return false;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuName() {
return stuName;
}
}
Main class
public class EqualsTest {
public static void main(String[] args) throws CloneNotSupportedException {
Student stu1 = new Student(100, "Lee");
Student stu2 = new Student(100, "Kim");
System.out.println("= equals 메소드 이용한 비교 =");
if (stu1.equals(stu2)) System.out.println("같은 객체");
else System.out.println("다른 객체");
System.out.println();
System.out.println("= stu1 == stu2 이용한 비교 =");
if (stu1 == stu2) System.out.println("같은 객체");
else System.out.println("다른 객체");
System.out.println();
System.out.println("= 재정의한 hashcode 메소드 이용한 비교 =");
System.out.println("hashcode stu1: " + stu1.hashCode());
System.out.println("hashcode stu2: " + stu2.hashCode());
System.out.println();
System.out.println("= 실제 객체의 주소 이용한 비교 =");
System.out.println("hashcode orginal stu1: " + System.identityHashCode(stu1));
System.out.println("hashcode orginal stu2: " + System.identityHashCode(stu2));
System.out.println();
System.out.println("= clone 메소드 이용 =");
Student copyStudent = (Student) stu1.clone();
System.out.print("stu1: " + System.identityHashCode(stu1));
System.out.println(", copyStu: " + System.identityHashCode(copyStudent));
stu1.setStuName("Park");
System.out.println(stu1.getStuName() + ", " + copyStudent.getStuName());
}
}
실행 결과
'백엔드 공부하기 > TIL' 카테고리의 다른 글
230807 TIL : Class 클래스 (0) | 2023.08.07 |
---|---|
230804 TIL : String, StringBuilder, StringBuffer, text block (0) | 2023.08.04 |
230803 TIL : 상속 및 인터페이스와 추상클래스의 차이 (0) | 2023.08.03 |
230802 TIL : 자바 인터페이스 정리 (0) | 2023.08.03 |
230801 TIL : 업캐스팅의 이유, 템플릿 메소드, 프레임워크와 라이브러리의 차이 (0) | 2023.08.01 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 채팅기능개발
- 부트캠프
- 그룹스터디
- qjzl
- 스터디후기
- 데이터베이스
- boj
- Java
- 패스트캠퍼스
- 자료구조
- 카카오API
- TiL
- be
- 야놀자X패스트캠퍼스부트캠프
- 국비지원
- 국비지원캠프
- 백엔드개발자
- 패스트캠퍼스강의
- #국비지원취업
- 야놀자
- 커리어멘토링
- 자료구조 #스택 #큐 #덱 #선형자료구조
- 백준
- 백엔드
- 과정중간회고
- 프로젝트후기
- 그룹스터디워크샵
- 백엔드부트캠프
- 국비지원취업
- springboot
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함