This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
I've often wished that the JavaBean specification included this feature for setters so that one can chain them as such, but as James pointed out, this is not a valid bean construct. In fact, defining setters to return anything other than void will break lots of things that expect JavaBeans.
Tejas Jain wrote:I saw someone did something like:
User user = new User(); //User is a Java Bean
user.setName("John Smith").setPhone("800-123-4567").print(); // This is a new syntax to me. From which version does it start? I did not see this in Java 5
Check out StringBuffer, available since Java 1.0, which uses the same technique. As Bear said, this is called chaining. It's the same as the following, provided setName and setPhone return a reference to the current object ("this"):