Originally posted by Prasad Maddipatla:
class A
{
int x = 5;
}
class B extends A
{
int x = 6;
}
public class CT
{
public A getObject()
{
return new A();
}
public static void main(String[] arg)
{
CT c = new SCT();
System.out.println(c.getObject());//1
System.out.println(c.getObject().x);//2
}
}
class SCT extends CT
{
public B getObject()
{
return new B();
}
In the above question at line //1 i am getting object B, then why at line //2 i am getting output as 5 which which is the value of Object A.
Can any body clarify this puzzle.
Hi Prasad, your code and output of your code everything is fine.I like to add one point.
Whenever you try to call like c.getObject().Always extended class is called.And also whenever you try to access instance variables only parent class will be called.To get clear knowledge you pleas try the following code.
In the above program //1 --> class SCT is called and corresponding class B is called.
//2 --> class SCT is called and corresponding sample() in class B is called.
From this you can conclude that only instance variables can be accessable in that way.Hope this help you..
-Thanks & Regards,
Hamsa