자바 에서 toString 방법 상세 설명
5351 단어 자바
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
원본 코드 에 따 르 면 반환 값 은 클래스 이름 + 기호 @ + 대상 의 해시 코드 값 입 니 다.원본 코드 주석 에서 중요 한 한 마디 가 있 습 니 다. It is recommended that all subclasses override this method (모든 하위 클래스 가 이 방법 을 덮어 쓰 는 것 을 권장 합 니 다), 자바 류 는 필요 에 따라 toString 방법 을 다시 써 야 반환 값 을 더욱 의미 있 게 할 수 있 습 니 다.
2. toString 방법 을 다시 쓰 지 않 습 니 다. 예 는 다음 과 같 습 니 다.
public class DemoApplicationTests {
public static void main (String[] args){
Point p = new Point(1,2);
System.out.println(p.toString());
}
}
class Point{
private int x;
private int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
출력 결과 (클래스 이름 + 기호 @ + 대상 의 해시 코드 값):
Point@6267c3bb
3. toString 재 작성 방법, 예 는 다음 과 같 습 니 다.
public class DemoApplicationTests {
public static void main (String[] args){
Point p = new Point(1,2);
System.out.println(p.toString());
}
}
class Point{
private int x;
private int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
// toString
public String toString(){
return "x=" + x + ",y=" + y;
}
}
출력 결과 (필요 에 따라 문자열 입력):
x=1,y=2
4. 위의 두 가지 예 중
System.out.println(p.toString());
약자
System.out.println(p);
System. out. println 방법 은 대상 의 toString 방법 을 자동 으로 호출 하여 되 돌아 오 는 문자열 을 출력 하기 때 문 입 니 다.
5. 다음은 String 류 의 예 를 살 펴 보 겠 습 니 다.
public static void main (String[] args){
String str = new String("Hello");
System.out.println(str);
}
출력 결과:
Hello
그러면 우 리 는 toString 방법 을 다시 쓰 지 않 았 습 니 다. 왜 출력 결 과 는 '클래스 + 기호 @ + 대상 의 해시 코드' 형식 이 아니 라 문자열 입 니까?이것 은 String 이 우리 대신 toString 방법 을 다시 썼 기 때 문 입 니 다. 문자열 자 체 를 직접 되 돌려 줍 니 다. 다음은 String 클래스 의 원본 코드 를 보십시오.
/**
* This object (which is already a string!) is itself returned.
*
* @return the string itself.
*/
public String toString() {
return this;
}
요약: