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).
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.
I was able to get it to compile by typecasting a to class B as follows...
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 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 ---
which I'm pretty sure is not what was intended.
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.