Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.help > #1554

Re: Interchanging objects?

From Eric Sosman <esosman@ieee-dot-org.invalid>
Newsgroups comp.lang.java.help
Subject Re: Interchanging objects?
Date 2012-02-07 08:09 -0500
Organization A noiseless patient Spider
Message-ID <jgr7r2$cn9$1@dont-email.me> (permalink)
References <bb014e7e-2bf1-4d55-8677-6e2514826da5@p7g2000yqk.googlegroups.com>

Show all headers | View raw


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

Back to comp.lang.java.help | Previous | NextPrevious in thread | Find similar


Thread

Interchanging objects? Davej <galt_57@hotmail.com> - 2012-02-04 12:02 -0800
  Re: Interchanging objects? Lew <lewbloch@gmail.com> - 2012-02-04 23:00 -0800
    Re: Interchanging objects? Davej <galt_57@hotmail.com> - 2012-02-05 07:41 -0800
      Re: Interchanging objects? Lew <lewbloch@gmail.com> - 2012-02-05 11:34 -0800
      Re: Interchanging objects? Roedy Green <see_website@mindprod.com.invalid> - 2012-02-08 22:42 -0800
        Re: Interchanging objects? Lew <lewbloch@gmail.com> - 2012-02-09 09:21 -0800
  Re: Interchanging objects? Eric Sosman <esosman@ieee-dot-org.invalid> - 2012-02-07 08:09 -0500

csiph-web