weired output

G

gk

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 ?
 
R

Ralf Seitner

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top