weired output

Discussion in 'Java' started by gk, Nov 4, 2006.

  1. gk

    gk Guest

    class Test
    {
    public static void main(String [ ] args)
    {
    Base b = new Subclass();
    System.out.println(b.x); // this access from Base
    System.out.println(b.method());// this access from Subclass
    }
    }


    class Base
    {
    int x = 2;
    int method()
    {
    return x;
    }
    }


    class Subclass extends Base
    {
    int x = 3;
    int method()
    {
    return x;
    }
    }


    output:
    ----------

    2
    3



    just look at the code in above

    do you see ?
    Base b = new Subclass();

    it is asking , value of b.x and b.method()

    I am very surprised , b has taken the x value from class Base and
    method() from Subclass .

    why ?

    it should take both the value from Subclass .....why ? well, because
    the real object is a Subclass object and b is a just a reference
    .......so b should pull out BOTH the values from the Subclass object.

    why it picked up ONE value from Base class and OTHER value from
    Subclass ?
    gk, Nov 4, 2006
    #1
    1. Advertising

  2. gk

    Ralf Seitner Guest


    > I am very surprised , b has taken the x value from class Base and
    > method() from Subclass .
    >
    > why ?
    >

    Hi!
    Methods are bound dynamically, variables are not. That's why.
    bye, Ralf
    Ralf Seitner, Nov 4, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Nedu N
    Replies:
    1
    Views:
    380
    Steven Cheng[MSFT]
    Jan 21, 2004
  2. Nedu N
    Replies:
    5
    Views:
    628
    Steven Cheng[MSFT]
    Mar 6, 2004
  3. =?Utf-8?B?QW5kcmV3?=

    Weired start page...

    =?Utf-8?B?QW5kcmV3?=, Dec 2, 2005, in forum: ASP .Net
    Replies:
    1
    Views:
    342
    James Fujino
    Dec 3, 2005
  4. Annie
    Replies:
    4
    Views:
    690
    Annie
    Apr 24, 2007
  5. Wei
    Replies:
    7
    Views:
    301
    Sylvester Hesp
    May 25, 2007
Loading...

Share This Page