공부/Spring

[Java] toString() - 객체에 정의시 출력문에서 자동 호출되는 함수

leejinwoo1126 2021. 10. 6. 21:56
반응형

핵심

  • java 정의된 모든 class 는 최상위 Object 객체를 상속받음
    • extends 를 붙이지 않아도 java.lang.Object 상속받음
  • Object class의 메소드 중 toString()을 사용자 정의 객체에서 오버라이딩(Overiding,재정의) 할 경우
    • System.out.println(객체); 로 호출시 객체에서 재정의한 toString()이 자동으로 호출되도록 약속되어 있다

예시 Student.java

public class Student implements Comparable<Student>{

    private int no;
    private String name;
    private int score;

    public Student(int no, String name, int score){
        this.no = no;
        this.name = name;
        this.score = score;
    }

    // getter, setter 생략

    public String toString(){ // 오버라이딩
        return "( no : " + this.no + ", name : " + name + ", scroe :" + this.score + ")";
    }

    @Override
    public int compareTo(Student o) {
        return this.no - o.getNo();
    }

}

예시 Test.java


public static void main(String[] args) {

        ArrayList<Student> list = new ArrayList<>(); // 

        list.add(new Student(2, "홍길동", 96));
        list.add(new Student(1, "이순신", 89));
        list.add(new Student(3, "김철수", 50));
        list.add(new Student(4, "최영희", 70));

        Collections.sort(list); // Student 클래스에서 구현한 Comparable 인터페이스 함수 기준으로 정렬함 , no 오름차순

        for(Student obj : list){
            System.out.println(obj); // toString()이 암묵적으로 호출됨
            //System.out.println(obj.getNo() + ", "+ obj.getName()+ ", " + obj.getScore());
        }
 }
  • 출력결과
    ( no : 1, name : 이순신, scroe :89)
    ( no : 2, name : 홍길동, scroe :96)
    ( no : 3, name : 김철수, scroe :50)
    ( no : 4, name : 최영희, scroe :70)

참고

https://edu.goorm.io/learn/lecture/41/%EB%B0%94%EB%A1%9C%EC%8B%A4%EC%8A%B5-%EC%83%9D%ED%99%9C%EC%BD%94%EB%94%A9-%EC%9E%90%EB%B0%94-java/lesson/770/tostring
https://onsil-thegreenhouse.github.io/programming/java/2017/11/19/java_tutorial_1-12/

반응형