wood burning stoves 2.0*
The moose likes Java in General and the fly likes New syntax in Java 6? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "New syntax in Java 6?" Watch "New syntax in Java 6?" New topic
Author

New syntax in Java 6?

Tejas Jain
Ranch Hand

Joined: Mar 04, 2008
Posts: 119
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


"Knowing is not enough, you must apply... Willing is not enough, you must do."
--Bruce Lee
James Sabre
Ranch Hand

Joined: Sep 07, 2004
Posts: 781

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.


Retired horse trader.
 Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61095
    
  66

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.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19682
    
  20

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"):


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61095
    
  66

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: New syntax in Java 6?