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


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

Re: Java casting question

Date 2011-10-12 21:36 -0400
From Arne Vajhøj <arne@vajhoej.dk>
Newsgroups comp.lang.java.programmer
Subject Re: Java casting question
References <c6d9d3ed-7892-40e0-ac9a-abb957b93241@e9g2000prg.googlegroups.com>
Message-ID <4e964097$0$281$14726298@news.sunsite.dk> (permalink)
Organization SunSITE.dk - Supporting Open source

Show all headers | View raw


On 10/12/2011 9:27 PM, Chad wrote:
> Given the following...
>
> class X {
>      void f1() { System.out.println("XXX");}
>      void f2() { System.out.println("AAA"); f1();}
> }
>
> class Y extends X {
>      void f1() { System.out.println("YYY"); }
> }
>
> class Z extends X {
>      void f1() { System.out.println("ZZZ"); }
> }
> public class Main {
>
>      static void g(X a) {
>          a.f2();
>      }
>      public static void main(String[] args) {
>          X x = new X();
>          Y y = new Y();
>          Z z = new Z();
>
>          Object obj = new Y();
>          ((X) obj).f2();
>          g(z);
>          //y = (Y)x;
>      }
>
> }
>
> I get the following output..
>
> AAA
> YYY
> AAA
> ZZZ
>
>
> The question is about
>
> Object obj = new Y();
> ((X) obj).f2();
>
>
> How come YYY, but not XXX, gets printed on the second line? Both f1()
> and f2() are in class X. So shouldn't f1() also have been casted to
> (type) X?

((X) obj).f2();

and

((Y) obj).f2();

should give the same output.

Virtual methods are stored in the object and it really
does not matter what type the ref is declared to.

Arne

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