'#Object클래스'에 해당되는 글 1건

자바에서 모든 클래스는 java.lang 패키지에 선언된 Object 클래스를 상속 받는다.
클래스를 상속받을 때는 import 문으로 해당클래스를 선언해야하는데 java.lang 패키지의 경우에는 컴파일 과정에서 자동으로 모든 클래스에 암묵적으로 선언된다.

이제부터 Object 클래스에 선언된 메서드들의 대해서 알아보자.

toString 메서드

Book 클래스

package object;

class Book {
    int bookNumber;
    String bookTitle;

    Book(int bookNumber, String bookTitle) {
        this.bookNumber = bookNumber;
        this.bookTitle = bookTitle;
    }
}

public class ToStringEx {
    public static void main(String[] args) {
        Book book1 = new Book(200, "개미");

        System.out.println(book1);
        System.out.println(book1.toString());
    }

}

  • Book 객체의 인스턴스를 생성해 그 주소값을 출력하였다.
  • 그냥 book1 을 호출하여도 book1.toString과 같은 결과값이 나온다.
  • 사실, 인스턴스를 호출하면 내부적으로 toString() 메서드를 호출하고 있는 것이다.
  • 그러면 String, Integer 도 클래스라고 하는데 왜 주소값이 아닌, 그냥 값이 출력되는 것일까? 그것은 Object 클래스의 toString 메서드가 재정의되었기 때문이다.
  • 그럼 위의 Book 클래스도 입력한 값이 출력 되도록 toString 메서드를 재정의 해보자.

toString 메서드를 재정의한 Book 클래스

package object;

class Book {
    int bookNumber;
    String bookTitle;

    Book(int bookNumber, String bookTitle) {
        this.bookNumber = bookNumber;
        this.bookTitle = bookTitle;
    }


    @Override
    public String toString() {
        return "Book [bookNumber=" + bookNumber + ", bookTitle=" + bookTitle + "]";
    }

}

public class ToStringEx {
    public static void main(String[] args) {
        Book book1 = new Book(200, "개미");

        System.out.println(book1);
        System.out.println(book1.toString());
    }

}

  • 위와 같이 변수에 입력한 값들이 출력되었다.

equals 메서드

equals 메서드는 참조값의 논리적인 비교를 하는 메서드이다.

EqualsTest

package object;

class Student {
    int studentId;
    String studentName;

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

    public String toString() {
        return studentId + "," + studentName;
    }

}

public class EqualsTest {
    public static void main(String[] args) {
        Student studentLee = new Student(100, "이상원");
        Student studentLee2 = studentLee;
        Student studentSang = new Student(100, "이상원");


        if(studentLee == studentLee2) {
            System.out.println("studentLee와 studentLee2의 주소는 같습니다.");
        }else {
            System.out.println("studentLee와 studentLee2의 주소는 다릅니다.");
        }

        if(studentLee.equals(studentLee2)) {
            System.out.println("studentLee와 studentLee2 는 동일합니다.");
        }else {
            System.out.println("studentLee와 studentLee2 는 동일하지 않습니다.");
        }

        System.out.println("");

        if(studentLee == studentSang) {
            System.out.println("studentLee와 studentSang의 주소는 같습니다."); 
        }else {
            System.out.println("studentLee와 studentSang의 주소는 다릅니다.");
        }

        if(studentLee.equals(studentSang)) {
            System.out.println("studentLee와 studentSang 는 동일합니다.");
        }else {
            System.out.println("studentLee와 studentSang 는 동일하지 않습니다.");
        }        

    }
}

  • 일반 클래스에서는 동등연산자(==) 와 동일한 기능을 하는 것을 볼 수 있다. 하지만,

StringEquals 클래스

package object;

public class StringEquals {
    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)); // 논리적으로 같음.


        System.out.println();

        Integer i1 = new Integer(100);
        Integer i2 = new Integer(100);


        System.out.println(i1 == i2);
        System.out.println(i1.equals(i2));


    }
}

  • String 와 Integer는 논리적인 값을 비교한다.
  • 이것은 앞의 toString 과 마찬가지로 equals() 메서드가 미리 재정의 되어있기 때문이다.

그러면 앞의 Student 클래스도 위와 같이 동작되도록 equals 메서드를 재정의 해보자.

Student 클래스의 equals 메서드 재정의

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

  • studentLee 와 studentSang 이 같을 경우를 보면 값이 같으므로 동일하다고 출력되는 걸 볼 수 있다.

equals 예제

package object;

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 dt = (MyDate)obj;
            if(dt.year == this.year && dt.month == this.month && dt.day == this.day) {
                return true;
            }else {
                return false;
            }
        }        
        return false;
    }

}

public class MyDateTest {
    public static void main(String[] args) {
        MyDate date1 = new MyDate(9, 18, 2004);
        MyDate date2 = new MyDate(9, 18, 2004);

        System.out.println(date1.equals(date2));
        System.out.println(date1 == date2);

    }
}

hashCode 메서드

hash는 정보를 저장하거나 검색할 때 사용하는 자료구조 이다.
일반적으로 equals 메서드를 재정의할때 그 정보의 값을 가르키는 hashCode도 재정의 하도록 한다.

Student 클래스 해쉬코드 메서드 재정의.

package object;

class Student {
    int studentId;
    String studentName;

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

    public String toString() {
        return studentId + "," + studentName;
    }

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

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

}

public class EqualsTest {
    public static void main(String[] args) {
        Student studentLee = new Student(100, "이상원");
        Student studentLee2 = studentLee;
        Student studentSang = new Student(100, "이상원");


        if(studentLee == studentLee2) {
            System.out.println("studentLee와 studentLee2의 주소는 같습니다.");
        }else {
            System.out.println("studentLee와 studentLee2의 주소는 다릅니다.");
        }

        if(studentLee.equals(studentLee2)) {
            System.out.println("studentLee와 studentLee2는 동일합니다.");
        }else {
            System.out.println("studentLee와 studentLee2는 동일하지 않습니다.");
        }

        System.out.println("");

        if(studentLee == studentSang) {
            System.out.println("studentLee와 studentSang의 주소는 같습니다."); 
        }else {
            System.out.println("studentLee와 studentSang의 주소는 다릅니다.");
        }

        if(studentLee.equals(studentSang)) {
            System.out.println("studentLee와 studentSang는 동일합니다.");
        }else {
            System.out.println("studentLee와 studentSang는 동일하지 않습니다.");
        }        

        System.out.println(studentLee.hashCode());
        System.out.println(studentSang.hashCode());

        System.out.println();

        System.out.println(System.identityHashCode(studentLee));  // 실제 주소값
        System.out.println(System.identityHashCode(studentSang)); // 실제 주소값

    }
}

  • 학번이 같다는 것을 알려주기 위해 해쉬코드로 학번을 리턴한다.

clone 메서드

객체의 원본은 그대로 놔두고 인스턴스의 값만 복사할 때 사용한다.

ObjectCloneTest 클래스

package object;

class Point {
    int x; // 10
    int y; // 20

    Point(int x, int y){
        this.x = x;
        this.y = y;
    }

    public String toString() {
        return "x=" + x + "," + "y = " + y;
    }
}

class Circle implements Cloneable {
    Point point;
    int radius; // 30

    Circle(int x, int y, int radius) {
        this.radius = radius;
        point = new Point(x, y);
    }

    public String toString() {
        return "원점은 " + point + "이고," + "반지름은 " + radius + "입니다.";
    }


    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}


public class ObjectCloneTest {
    public static void main(String[] args) throws CloneNotSupportedException {
        Circle circle = new Circle(10, 20, 30);
        Circle copyCircle = (Circle)circle.clone();

        System.out.println(circle);
        System.out.println(copyCircle);
        System.out.println(System.identityHashCode(circle));
        System.out.println(System.identityHashCode(copyCircle));
        System.out.println(circle == copyCircle);

    }
}

출처: do it 자바프로그래밍

'프로그래밍 > Java' 카테고리의 다른 글

wrapper클래스  (0) 2019.12.11
String 클래스  (0) 2019.12.10
인터페이스의 구현과 상속  (0) 2019.12.08
인터페이스 - 디폴트메서드, 정적메서드  (0) 2019.12.08
jdk환경변수 설정하기 (feat. window10)  (0) 2019.12.08
블로그 이미지

파니동

,