Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!newsreader4.netcologne.de!news.netcologne.de!.POSTED!not-for-mail From: Patrick Roemer Newsgroups: comp.lang.java.programmer Subject: Re: can this be done with generics? Date: Mon, 25 Nov 2013 12:59:29 +0100 Organization: news.netcologne.de Lines: 52 Distribution: world Message-ID: References: NNTP-Posting-Host: xdsl-78-35-78-104.netcologne.de Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit X-Trace: newsreader4.netcologne.de 1385380769 4968 78.35.78.104 (25 Nov 2013 11:59:29 GMT) X-Complaints-To: abuse@netcologne.de NNTP-Posting-Date: Mon, 25 Nov 2013 11:59:29 +0000 (UTC) User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.24) Gecko/20100411 Thunderbird/2.0.0.24 Mnenhy/0.7.6.0 In-Reply-To: Xref: csiph.com comp.lang.java.programmer:26608 Responding to Andreas Leitgeb: > class Foo { > public Foo foo1() { > /* do something very interesting ... */ > return this; > } > // assume there were like 100 such foo#() methods here > // (in practice they of course have more diverse names) > } > class Bar extends Foo { > public Bar bar() { > /* do something very interesting */ > return this; > } > } [...] > // but if I start with a Bar, and eventually after some foo#() calls > // want to call method bar() which is not in Foo, then I'm out of luck: > new Bar().foo1().foo42().foo84().bar(); // doesn't work, of course! > > Is there a way to use *generics* for the methods of class Foo such that > each foo#() returns the *static* type on which the compiler saw it > applied? Just a naive attempt... Not sure if this matches your use case and requirements - this will only work for a one-level hierarchy with an abstract root class and will probably require some ugly gymnastics inside the Foo method implementations: abstract class Foo> { protected abstract T self(); public T foo1() { return self(); } } class Bar extends Foo { public Bar bar() { return this; } @Override protected Bar self() { return this; } } Best regards, Patrick