Menu
Coddy logo textTech

toString() 메서드

Coddy Java 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 87개 중 41번째.

Java의 모든 class는 여러 유용한 method를 제공하는 Object class를 상속합니다. 가장 흔히 재정의되는 method 중 하나는 객체의 문자열 표현을 반환하는 toString()입니다.

기본적으로 toString()은 클래스 이름 뒤에 객체의 해시 코드를 반환하므로 그다지 유용하지 않습니다.

public class Person {
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

Person p = new Person("Alice", 25);
System.out.println(p);  // Person@15db9742

toString()을 오버라이드하면 객체의 상태를 설명하는 의미 있는 출력을 제공할 수 있습니다.

public class Person {
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "Person[name=" + name + ", age=" + age + "]";
    }
}

Person p = new Person("Alice", 25);
System.out.println(p);  // Person[name=Alice, age=25]

toString() method는 object를 출력하거나 string과 연결할 때 automatically 호출됩니다. 추가 코드를 작성하지 않고도 object의 내용을 빠르게 확인할 수 있으므로 디버깅이 훨씬 쉬워집니다.

challenge icon

챌린지

쉬움

사용자 지정 toString() 구현을 사용하여 항목에 대한 의미 있는 정보를 표시하는 product inventory system을 만들어 보겠습니다. 기본 toString() method를 재정의하여 각 product를 명확하고 읽기 쉬운 표현으로 제공하는 Product class를 만들게 됩니다.

코드를 두 개의 파일로 구성합니다.

  • Product.java: inventory item을 나타내는 class를 Create합니다. 각 Product에는 세 개의 private fields가 있습니다: name (String), price (double), quantity (int). 세 fields를 모두 initializes하는 Constructor를 포함합니다. toString() method를 Override하여 다음의 정확한 format으로 formatted string을 Return합니다: Product[name=X, price=Y, quantity=Z]. 여기서 X, Y, Z는 actual field values입니다. price는 일반 숫자로 표시하면 됩니다(특별한 format은 필요하지 않음).
  • Main.java: product를 Create하고 표시하여 Product class를 실제로 사용해 봅니다. 세 개의 inputs를 받습니다: product name (String), price (double), quantity (int). 이 values로 Product를 Create한 다음 System.out.println()을 사용하여 product object를 directly Print합니다. 재정의한 toString() method 덕분에 cryptic한 기본 출력 대신 formatted product information이 automatically 표시됩니다!

세 개의 inputs를 받습니다: product name (String), price (double), quantity (int).

object를 directly Print하면 toString() method가 automatically call된다는 점에 주목하세요. 이것이 실제 applications에서 debugging과 logging을 훨씬 쉽게 만드는 이유입니다!

REQUIRED OUTPUT FORMAT: [Your translated content here]

직접 해보기

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // 입력 읽기
        String name = scanner.nextLine();
        double price = scanner.nextDouble();
        int quantity = scanner.nextInt();
        
        // TODO: 입력 값으로 Product 객체 생성
        
        // TODO: product 객체를 직접 출력
        // (이렇게 하면 자동으로 toString() 메서드가 호출됩니다!)
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Java 컴파일러