Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

New syntax in Java 6?

 
Tejas Jain
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
James Sabre
Ranch Hand
Posts: 781
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is not a Java version thing. It seems that the writer of the class User defined methods along the lines of


I use this approach sometimes but never for Java beans. Usually only when I want to set a property of an agent type class.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65111
89
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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"):
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65111
89
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And just to emphasize: this is nothing new in Java 6, or any other version of Java. It's simply a matter of defining methods to allow this.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic