Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!weretis.net!feeder1.news.weretis.net!feeder.erje.net!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.help Subject: Re: Interchanging objects? Date: Tue, 07 Feb 2012 08:09:51 -0500 Organization: A noiseless patient Spider Lines: 62 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Tue, 7 Feb 2012 13:09:54 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="HSlJAUb3pGXi3i7ZL/HoAw"; logging-data="13033"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18f6NmnR+Zt1gazP/mAJWQg" User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:10.0) Gecko/20120129 Thunderbird/10.0 In-Reply-To: Cancel-Lock: sha1:D9S213pcgdiJzNCFHDwtoj+qBRY= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.help:1554 On 2/4/2012 3:02 PM, Davej wrote: > If two objects have the same method names, can one of them be cast as > the other? No, not unless one subclasses the other and the cast is "upward." The fact that Pistol and Petunia both have shoot() methods does not imply that one can be treated as the other. If the methods in question are specified by an interface and both classes implement that interface, then an instance of either class can be treated as an "instance" of the interface: interface Portable { void carry(); } class Luggage implements Portable { void carry() { ... }; } class Tune implements Portable { void carry() { ... }; } In a situation like this, you can do: Portable p1 = new Luggage(); Portable p2 = new Tune(); Portable p3 = choose() ? p1 : p2; p3.carry(); ... and so on, without so much as a cast. But you still can't convert a Luggage to a Tune or vice versa; you can only use the fact that both classes are Portable. Something very similar can be done if the methods are specified by a common ancestral class (perhaps an abstract class): class SportsFan { void cheer() { ... }; } class GiantsFan extends SportsFan { @Override void cheer() { ... }; } class PatriotsFan extends SportsFan { @Override void cheer() { ... }; } SportsFan f1 = new GiantsFan(); SportsFan f2 = new PatriotsFan(); SportsFan f3 = choose() ? f1 : f2; f3.cheer(); GiantsFan instances and PatriotsFan instances are all SportsFan instances and can be treated as such, but you still can't make a GiantsFan of a PatriotsFan. -- Eric Sosman esosman@ieee-dot-org.invalid