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