public class Person {
private String name;
private int age;
public Person setName(String name) {
this.name = name;
return this; // 현재 객체를 반환하여 메서드 체이닝을 가능하게 함
}
public Person setAge(int age) {
this.age = age;
return this;
}
public void printPerson() {
System.out.println("Name: "+ name + ", Age: " + age);
}
public static void main(String[] args) {
Person person = new Person();
person.setName("Alice").setAge(30).printPerson();
}
}
📌 출력
Name: Alice, Age: 30
setName()
과 setName()
메서드가 Person
객체를 반환하기 때문에 메서드 체이닝이 가능함.class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
setName(name) {
this.name = name;
return this; // 현재 객체를 반환하여 체이닝 가능하게 함
}
setAge(age) {
this.age = age;
return this;
}
printPerson() {
console.log(`Name: ${this.name}, Age: ${this.age}`);
return this;
}
}
const person = new Person();
person.setName("Alice").setAge(30).printPerson();
📌 출력
Name: Alice, Age: 30
this
객체를 반환해야 함.String
클래스는 불변(immutable) 객체이기 때문에 체이닝을 사용해도 원본 객체는 변하지 않음.@RequestMapping(value = "/example", method = RequestMethod.GET)
public ResponseEntity<String> example() {
return ResponseEntity
.status(HttpStatus.OK)
.header("Content-Type", "application/json")
.body("{\"message\":\"Hello, World!\"}");
}