toString()메서드의 구조는getClass().getName() + '@' + Integer.toHexString(hashCode()) 입니다. 여기서 사용되는hashCode() 는 주소값을 반환하는 메서드 이고
반환값이 정수형(int)이여서 객체의 주소값을 10진수로 반환합니다.
package object;
class Food{
int foodCode;
String food;
public Food(int foodCode, String food) {
this.foodCode = foodCode;
this.food = food;
}
@Override
public int hashCode() {
return foodCode;
}
}
public class HashCodeEx {
public static void main(String[] args) {
Food food1 = new Food(1000, "사과");
Food food2 = new Food(1000, "사과");
System.out.println(food1.hashCode()); //결과값(오버라이딩전) : 1028566121 , 결과값(오버라이딩후) : 1000
System.out.println(food2.hashCode()); //결과값(오버라이딩전) : 1118140819 , 결과값(오버라이딩후) : 1000
System.out.println(System.identityHashCode(food1)); //결과값 : 1028566121
System.out.println(System.identityHashCode(food2)); //결과값 : 1118140819
}
}
* 실제 주소값을 반환하려면 System.identityHashCode() 를 사용하면 됩니다.
clone() : 이 개체의 복사본을 만들고 반환
개체의 원본을 유지하고 틀만 복사본을 만드는 것.
메모리 주소가 다른 인스턴스가 생성됩니다.
clone() 메서드를 사용할 때 발생할 수 있는 오류를 예외처리해주어야 합니다.
=> throws CloneNotSupportedException
clone()메서드를 사용하는 클래스 에 Cloneable 인스턴스를 선언하여 복제를 허용해주어야 합니다.
* Cloneable 를 선언하지 않으면 Exception in thread "main" java.lang.CloneNotSupportedException: object.Circle 오류발생
package object;
class Point{
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
}
class Circle implements Cloneable{
Point point;
int radius;
public Circle(int x, int y, int radius) {
this.radius = radius;
point = new Point(x, y);
}
@Override
public String toString() {
return "Circle [point=" + point + ", radius=" + radius + "]";
}
@Override
protected Object clone() throws CloneNotSupportedException { // 예외처리
return super.clone();
}
}
public class ObjectCloneTest {
public static void main(String[] args) throws CloneNotSupportedException {
Circle c1 = new Circle(5, 10, 2);
Circle c1_1 = (Circle) c1.clone(); //clone()의 데이터 형이 Object여서 다운캐스팅
System.out.println(c1);
System.out.println(c1_1);
}
}
** java.lang.String, java.lang.Integer 등등 lang에 있는 클래스는
Object 메서드가 재정의 되어있어서 Override 하지 않아도 되지만 그 외의 클래스는 재정의 하여 사용해야 합니다.