Fluent setters with inheritance in java
<p>I've recently seen some code (amazon hadoop code) that utilizes this type of syntax</p>

<pre><code>Foo bar = new Foo().setX(10).setY(11);
</code></pre>

<p>I thought that was sweet so I decided to give it a go. made my <code>setX()</code> type functions return <code>Foo</code> instead of <code>void</code> and put <code>return this;</code> in all of them. this worked well. until I tried it with inheritance, which produced some strage results.</p>

<p>I'll give a concrete example: I have two classes, <code>Location</code> class that has two fields, x and y. and another class <code>Location3D</code> that inherits from <code>Location</code> and adds a third field, z.
all the fields use the method described above for their setters.</p>

<p>now I want to create a new location3D instance and set its fields, what happens is</p>

<pre><code>new Location3D().setZ(7).setY(6).setX(5)
</code></pre>

<p>works while</p>

<pre><code>new Location3D().setX(7).setY(6).setZ(5)
</code></pre>

<p>doesn't.</p>

<p>by doesn't work I mean that what returns from <code>setY(6)</code> is a <code>Location</code> object and not a <code>location3D</code> object and therefore does not have a <code>setZ()</code> method!</p>

<p>after this long intro my question is: can this form of "setter stringing" be made to work with inheritance without forcing the caller to cast objects ? if so how ?</p>

<p>also I'm sure there's a term for this better then "setter stringing", what is it ?</p>
