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


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

Java casting question

Path csiph.com!x330-a1.tempe.blueboxinc.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!nx02.iad01.newshosting.com!newshosting.com!69.16.185.11.MISMATCH!npeer01.iad.highwinds-media.com!news.highwinds-media.com!feed-me.highwinds-media.com!postnews.google.com!e9g2000prg.googlegroups.com!not-for-mail
From Chad <cdalten@gmail.com>
Newsgroups comp.lang.java.programmer
Subject Java casting question
Date Wed, 12 Oct 2011 18:27:29 -0700 (PDT)
Organization http://groups.google.com
Lines 51
Message-ID <c6d9d3ed-7892-40e0-ac9a-abb957b93241@e9g2000prg.googlegroups.com> (permalink)
NNTP-Posting-Host 66.81.51.98
Mime-Version 1.0
Content-Type text/plain; charset=ISO-8859-1
X-Trace posting.google.com 1318469249 11238 127.0.0.1 (13 Oct 2011 01:27:29 GMT)
X-Complaints-To groups-abuse@google.com
NNTP-Posting-Date Thu, 13 Oct 2011 01:27:29 +0000 (UTC)
Complaints-To groups-abuse@google.com
Injection-Info e9g2000prg.googlegroups.com; posting-host=66.81.51.98; posting-account=kTs1ygoAAACgG1TSoyECpovEyy-V6_8b
User-Agent G2/1.0
X-Google-Web-Client true
X-Google-Header-Order ARLUEHNKC
X-HTTP-UserAgent Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; InfoPath.2),gzip(gfe)
Xref x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:8748

Show key headers only | View raw


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?

Chad

Back to comp.lang.java.programmer | Previous | NextNext 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