Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2006

Tip: Looking for answers? Try searching our database.

weired  output

Thread view: 
gk - 04 Nov 2006 20:17 GMT
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 ?
Ralf Seitner - 04 Nov 2006 20:53 GMT
> 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


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.