Java Fluent Interface - Return Instance from Set Method
By admin on Dec 10, 2007 in Java, Others, Programming
Normally we create a class with the constructor, set/get methods as below
public class Person {
private String name;
private Integer age;
private String email;
public Person() {
}
public Person(String name, Integer age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
To set the properties values, either we can use the constructor or set/get methods
public static void main(String[] args){
Person p = new Person();
p.setName("Jason");
p.setEmail("jason@hotmail.com");
p.setAge(20);
}
I don’t remember the name of this pattern, but nowadays I tend to do this.
public class Person {
private String name;
private Integer age;
private String email;
public Person() {
}
public Person(String name, Integer age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
public String getName() {
return name;
}
public Person setName(String name) {
this.name = name;
return this;
}
public Integer getAge() {
return age;
}
public Person setAge(Integer age) {
this.age = age;
return this;
}
public String getEmail() {
return email;
}
public Person setEmail(String email) {
this.email = email;
return this;
}
public static void main(String[] args){
Person p = new Person();
p.setName("jason").setEmail("jason@hotmail.com").setAge(20);
}
}
UPDATE:
This is actually called fluent interface
A description of .NET implementation.

Kedar Mhaswade | Dec 12, 2007 | Reply
I think it’s called decorator pattern.
But just curious — why wouldn’t you make this
“value” class final and immutable? It solves all
sorts of problems, especially with value classes.
- Kedar
IllishEsseply | Jan 3, 2009 | Reply
qfqwwydumyzgogapwell, hi admin adn people nice forum indeed. how’s life? hope it’s introduce branch