[Java] 체인호출, toString() 재정의

원서연·2023년 11월 8일
0

체인호출이란.

    public static void main(String[] args) {
        Article article = new Article();

        // 일반적인 방식
        article.setTitle("Hello");
        article.setWriterName("Paul");
        article.setContent("Wolrd");

        // 체인호출 방식
        article
                .setTitle("Hello")
                .setWriterName("Paul")
                .setContent("World");
    }
  • 위 예제와 같이, 메서드 호출 결과로 객체 자신이 반환되어, 연이은 메서드 호출을 실행하는 것
  • 보통 위와 같이 객체에서 한 줄 띄고 들여쓰기를 하여 작성한다.
  • 체인호출을 사용하는 것은 필수가 아니며, 단지 개발자의 취향이라고 볼 수 있다.
    • 본인은 개인적으로 체인호출을 하면 가독성이 좋아진다고 생각하여, 자주 사용할 것 같다.
  • 다만, 사용하기 위해서는 준비사항이 필요하다. 메서드가 객체 자신을 반환해야한다.

체인호출 사용 준비

class Article {
    private String title;
    private String writerName;
    private String content;

    public Article setContent(String content) {
        this.content = content;

        return this;
    }

    public Article setWriterName(String writerName) {
        this.writerName = writerName;

        return this;
    }

    public Article setTitle(String title) {
        this.title = title;

        return this;
    }
}
  • Getter, Setter를 기본적으로 생성하게 되면, 반환 타입이 void이다.
  • 즉 메서드 실행 결과로 아무것도 반환하지 않아서, 체인호출을 할 수 없다.
  • 체인호출을 지원하도록 만들기 위해, 반환타입을 자기 자신을 지정하고 실행 결과로 반환한다.

toString() 재정의

package com.ll;

public class Main {
    public static void main(String[] args) {
        Article article = new Article("Hello", "world");
        
        System.out.println(article); // 출력 : {title='Hello', content='world'}
        // 재정의 안했을 때의 출력 : com.ll.Article@6e8cf4c6
    }
}

class Article extends Object{
    private String title;
    private String content;

    public Article(String title, String content) {
        this.title = title;
        this.content = content;
    }
    
    @Override
    public String toString() {
        return String.format("{title='%s', content='%s'}", title, content);
    }
}
  • 자바에서 모든 객체는 Object 클래스를 상속받는다.
    • 위 예제에서 extends Object는 작성하지 않아도 되는데, 예제로서 명시적으로 작성했다.
  • Object 클래스에는 toString() 메서드가 정의되어 있고, 자식 클래스들은 이를 상속받는다.
  • 기본적인 toString() 메서드를 사용시, com.ll.Article@6e8cf4c6와 같이 출력이 된다.
  • 만약 개발자가 객체의 필드 값을 출력해서 확인하고 싶을 경우,
    혹은 개발자의 취향대로 위와 같이 toString()을 재정의해서 사용하면 유용하다.
profile
웹 백엔드 프로그래밍 Today I Learned

0개의 댓글