toString()
toString()은 인스턴스 변수에 저장된 값들을 문자열로 표현한다는 뜻인데
Object클래스에 정의된 toStirng은 다음과 같다.
public String toString() {
return getCalss().getName()+"@"+Integer.toHexString(hashCode());
}
toString()을 오버라이딩 하지 않는다면 위와 같이 클래스이름에 16진수의 해시코드르 얻게 될 것이다.
오버라이딩은 아래와 같이 해주자.
class Car {
String kind;
String color;
int door;
public Car(String kind, String color, int door) {
this.kind = kind;
this.color = color;
this.door = door;
}
@Override
public String toString(){
return "kind : " + this.kind + ", color : " + this.color + ", door : " + this.door;
}
}
class CarToStringTest {
public static void main(String[] args) {
Car c1 = new Car("SUV", "RED", 4);
Car c2 = new Car("SportCar", "BLACK", 2);
System.out.println(c1);
System.out.println(c2.toString());
}
}
/* 결과
kind : SUV, color : RED, door : 4
kind : SportCar, color : BLACK, door : 2
*/
댓글