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


Groups > comp.lang.java.programmer > #8756

Re: Java casting question

Newsgroups comp.lang.java.programmer
From Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at>
Subject Re: Java casting question
References <c6d9d3ed-7892-40e0-ac9a-abb957b93241@e9g2000prg.googlegroups.com> <4e964097$0$281$14726298@news.sunsite.dk> <4447573.399.1318471540216.JavaMail.geo-discussion-forums@prfp13>
Message-ID <slrnj9df30.6gl.avl@gamma.logic.tuwien.ac.at> (permalink)
Date 2011-10-13 10:24 +0000

Show all headers | View raw


Lew <lewbloch@gmail.com> 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 <lewbloch@gmail.com> 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.

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


Thread

Java casting question Chad <cdalten@gmail.com> - 2011-10-12 18:27 -0700
  Re: Java casting question Arne Vajhøj <arne@vajhoej.dk> - 2011-10-12 21:36 -0400
    Re: Java casting question Lew <lewbloch@gmail.com> - 2011-10-12 19:05 -0700
      Re: Java casting question Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2011-10-13 10:24 +0000
  Re: Java casting question Travers Naran <tnaran@gmail.com> - 2011-10-12 23:40 -0700

csiph-web