| Author |
Compile time error
|
Ram Chhabra
Ranch Hand
Joined: Jan 07, 2008
Posts: 48
|
|
Hi,
I was just come across one confusion. Below please see the code:
In above code i am getting compile time because in main() method on line System.out.println(a.i); it is not able to get the value of i.
Thanks,
Ram
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Any private member (field, method, nested classes) is only accessible from code inside the very same class.
Now class B also has a field "i" that has default (package) visibility, so that should be visible. The thing is, unlike methods, fields are not polymorphic - it uses the reference type (in this case A), not the actual type (in this case B).
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Fred Hamilton
Ranch Hand
Joined: May 13, 2009
Posts: 679
|
|
Ram Chhabra wrote:Hi,
I was just come across one confusion. Below please see the code:
In above code i am getting compile time because in main() method on line System.out.println(a.i); it is not able to get the value of i.
Thanks,
Ram
I was able to get it to compile by typecasting a to class B as follows...
System.out.println(((B) a).i);
I think this is more likely the answer you want than simply removing the private modifier on i in class A, which also compiles.
Maybe you need to brush up on your polymorphism
OK Rob got in ahead of me, in light of his comments on Polymorphism, I'm not sure how my answer applies.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
Your cast to B works, because then it is using the i field in class B - which is visible. It's still not using the i field in class A, but that's impossible with the private modifier.
|
 |
Fred Hamilton
Ranch Hand
Joined: May 13, 2009
Posts: 679
|
|
Rob Prime wrote:Your cast to B works, because then it is using the i field in class B - which is visible. It's still not using the i field in class A, but that's impossible with the private modifier.
Duly noted. In light of that, I'm not sure what you meant earlier by fields not being polymorphic, but I'll do the research and find out.
It is worth noting that simply making the variable public in A gives the result
--- Class B ---
0
which I'm pretty sure is not what was intended.
best regards.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Fred Hamilton wrote:Duly noted. In light of that, I'm not sure what you meant earlier by fields not being polymorphic, but I'll do the research and find out.
What I meant is that for fields, the reference type (A) is what determines from which class the field is actually accessed. With methods on the other hand, it's the actual runtime type (B) that determines from which class the method is actually accessed.
|
 |
Ram Chhabra
Ranch Hand
Joined: Jan 07, 2008
Posts: 48
|
|
|
Thanks everybody..... That clarify my doubt.
|
 |
 |
|
|
subject: Compile time error
|
|
|