Object 클래스 알아보기

suebeen·2021년 8월 8일
0

Java

목록 보기
6/7
post-thumbnail

모든 클래스의 최상위 클래스 Object

Object 클래스는 모든 자바 클래스의 최상위 클래스다. 따라서 모든 클래스는 Object 클래스로부터 상속을 받는다.

하지만 클래스를 만들 때 extends Object를 쓰지 않았는데요??!?! → 컴파일러가 자동으로 변환해준다.

JavaDoc에서 Object의 메서드를 살펴볼 수 있다.

TypeMethodDescription
StringtoString()객체를 문자열로 표현하여 반환합니다. 재정의하여 객체에 대한 설명이나 특정 멤버 변수 값을 반환합니다.
booleanequals(Object obj)두 인스턴스가 동일한지 여부를 반환합니다. 재정의하여 논리적으로 동일한 인스턴스임을 정의할 수 있습니다.
inthashCode()객체의 해시 코드 값을 반환합니다.
Objectclone()객체를 복제하여 동일한 멤버 변수 값을 가진 새로운 인스턴스를 생성합니다.
ClassgetClass()객체의 Class 클래스를 반환합니다.
voidfinalize()인스턴스가 힙 메모리에서 제거될 때 가비지 컬렉터(GC)에 의해 호출되는 메서드입니다. 네트워크 연결 해제, 열려 있는 파일 스트림 해제 등을 구현합니다.
voidwait()멀티스레드 프로그램에서 사용하는 메서드입니다. 스레드를 '기다리는 상태'(non runnable)로 만듭니다.
voidnotify()wait() 메서드에 의해 기다리고 있는 스레드(non runnable상태)를 실행 가능한 상태(runnable)로 가져옵니다.

Object 메서드 중에는 재정의할 수 있는 메서드도 있고, 그렇지 않은 메서드도 있다. final 예약어로 선언한 메서드는 자바 스레드에서 사용하거나 클래스를 로딩하는 등 자바 가상 머신과 관련된 메서드이기 때문에 재정의할 수 없다.

메서드를 한번 사용해보자!

  1. toString() : 학번과 이름을 출력하도록 재정의
  2. equals() : 학번과 이름이 동일하면 true를 반환하도록 재정의
  3. hashCode() : 학번을 출력하도록 재정의
  4. clone() : "클론되었습니다." 를 출력하도록 재정의
    • implements Cloneable 을 해주어야 함
    • throws CloneNotSupportedException 를 해주어야 함
Student.java
public class Student implements Cloneable {

    int studentId;
    String studentName;

    public Student(int id, String name) {
        this.studentId = id;
        this.studentName = name;
    }

    @Override
    public String toString() {
        return "[학번: " + studentId + ", 이름: " + studentName + "]";
    }

    @Override
    public boolean equals(Object obj) {
        if(obj instanceof Student) {
            Student std = (Student)obj;
            if(this.studentId == std.studentId && this.studentName == std.studentName) return true;
            return false;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return studentId;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        System.out.println("클론되었습니다.");
        return super.clone();
    }
}
Main.java
public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Student s1 = new Student(1001, "박수빈");
        Student s2 = new Student(1002, "스펜서");
        Student s3 = new Student(1003, "아만드");

        System.out.println(s1.toString());
        System.out.println(s2.studentName + "의 학번은 " + s2.hashCode() + "입니다.");

        if(s1.equals(s3)) {
            System.out.println(s1.toString() + "과" + s3.toString() + "은 동일인입니다.");
        } else {
            System.out.println(s1.toString() + "과" + s3.toString() + "은 동일인이 아닙니다.");
        }

        Student s4 = (Student)s1.clone();

        if(s1.equals(s4)) {
            System.out.println(s1.toString() + "과" + s4.toString() + "은 동일인입니다.");
        } else {
            System.out.println(s1.toString() + "과" + s4.toString() + "은 동일인이 아닙니다.");
        }
    }
}

실행결과

0개의 댓글