Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!news.stack.nl!aioe.org!.POSTED!not-for-mail From: Ricardo Palomaes Newsgroups: comp.lang.java.programmer Subject: Re: question about casting and inheritance Date: Thu, 09 Jan 2014 23:24:06 +0100 Organization: Aioe.org NNTP Server Lines: 43 Message-ID: References: <5dfabbeb-9201-488d-b56b-e1cef3913c92@googlegroups.com> NNTP-Posting-Host: slL9sg8FQ1JGRZMftNBN5Q.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable X-Complaints-To: abuse@aioe.org User-Agent: Mozilla/5.0 (X11; Linux i686; rv:26.0) Gecko/20100101 Firefox/26.0 SeaMonkey/2.23 X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.java.programmer:27268 El 09/01/14 19:48, marc.at.compass@gmail.com escribi=F3: > As you see variable a points to an instance of A and not to (an > instance of) B. In fact, variable "a" is a reference to an object of class A. Since class B extends A, an object of class B is also an object of class A (it is "just a more specific type of A"). Thus, when you do: a =3D b; a is referencing the same object than b, ie., an object of class B. While accessing that object from "a", it only can behave as a class A object, and you couldn't do a.uniqueMethodForB(). However, as soon as you access the object from b again, you can access again the methods exclusive of a class B object. Note that, during this sequence: a =3D b; b =3D (B) a; the object itself has not been touched nor modified at all; you only have modified the references "a" and "b" (and "b" has been modified only to leave exactly as it was). > I effectively say "treat a as if it is b". I can > even call a method on b that is unique for B. But a didn't point to > an instance of B in the first place at all! Yes, it did. At least, since you did a =3D b. :-) > Why is it the line b=3D(B)a; doesn't give me a ClassCastException > during runtime? Because a holds a reference to a class A object that happens also to be a class B object, so it is not wrong to reference as such. HTH