Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!newsfeed.utanet.at!newscore.univie.ac.at!aconews-feed.univie.ac.at!aconews.univie.ac.at!not-for-mail Newsgroups: comp.lang.java.programmer From: Andreas Leitgeb Subject: Re: Java casting question References: <4e964097$0$281$14726298@news.sunsite.dk> <4447573.399.1318471540216.JavaMail.geo-discussion-forums@prfp13> Reply-To: avl@logic.at User-Agent: slrn/pre0.9.9-111 (Linux) Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Message-ID: Date: 13 Oct 2011 10:24:32 GMT Lines: 53 NNTP-Posting-Host: gamma.logic.tuwien.ac.at X-Trace: 1318501472 tunews.univie.ac.at 11354 128.130.175.3 X-Complaints-To: abuse@tuwien.ac.at Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:8756 Lew wrote: > To put it another way, the object instance "knows" its own type. > You cannot call a method on the supertype that exists only in the > subtype, but if you call a method that exists in the supertype that > the instance's subtype overrides, you will get the overridden version. At compile-time, the static type determines which method signature is picked, but at runtime the actual implementation for that signature is picked based on the object's actual type. Here is another example: class Test { void f1(Test o) { System.out.println("Test.f1(Test)"); } } class SubTest extends Test { void f1(Test o) { System.out.println("SubTest.f1(Test)"); } void f1(SubTest o) { System.out.println("SubTest.f1(SubTest)"); } } public class Main { public static void main(String[] args) { SubTest st = new SubTest(); st .f1(st); ((Test) st) .f1(st); } } Output: SubTest.f1(SubTest) SubTest.f1(Test) This shows, how the compiler settles on a method: for the first call, the compiler sees static type SubTest, and from among the two over*loads* picks the one most specifically matching the static type of the arguments: f1(SubTest). for the second call, the compiler sees static type Test, and Test only has one version f1(Test), so the compiler picks that. At runtime, however, SubTest.f1(Test) is called, as the object itself is a SubTest. > This is a key to how object-oriented programming works. yup PS: (for Lew) Lew wrote: >>> Object obj = new Y(); >>> ((X) obj).f2(); > Casting from a type to a supertype is automatic, > so the '(X)' cast in your code is superfluous. The premise did not apply, thus neither does the conclusion.