Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method Chaining question

 
Saeed Amer
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there

I am almost 100% sure that method-chanining is supported in Java. I said "almost" because following chaining doesn't compile.

Here is the original piece of code:


I wanted to do something like this:


but this code doesn't compile.

OR in other words, why can't I do the following:



Could someone please elaborate the concept why Java compiler is not allowing to do this?

Regards,

Saeed
 
Henry Wong
author
Marshal
Pie
Posts: 21119
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could someone please elaborate the concept why Java compiler is not allowing to do this?


When you say this...



The compiler reads it as this...



Basically, you are asking the compiler to create a new GregorianCalendar object; using that object, call the set() method; and using whatever is returned from the set() method, call the getTimeInMillis() method. Since the set() method does actually return anything -- you can't dereference it to get to the getTimeInMillis() method.

If the set() method returns a copy of the original object -- like the methods of the StringBuffer class -- you can chain the methods.

Henry
 
Saeed Amer
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great - thank you for so simple explanation.

Regards,
Saeed
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic