SCJP 6, SCWCD 5, SCBCD 5
sandeeep shinde wrote: How am i able to access the name variable directly even if it is a private variable.
OCJP 6 (93%)
You're in the same class, it doesn't matter if it's a different instance!
SCJP 6, SCWCD 5, SCBCD 5
sandeeep shinde wrote:Thanks a lot for your replies guys.
So it means that the private variables just cannot be accessed from other classes.
If the instance is created in the same class itself the private variable of that instance can be accessed directly.
Please correct me if I got it wrong.
Freddy Wong wrote:Frankly speaking, you can access private variables from outside a class via reflection, but you shouldn't do that unless you have a very good reason to do so.
SCJP 6, SCWCD 5, SCBCD 5
Lee Kian Giap wrote:
Are you trying to say using an inner class with inheritance to expose the private member of enclosing class ?
OCJP 6 (93%)
uj nossnahoj wrote:
The reason for this behavior is quite obvious if you think about it. Otherwise many (or even most) classes would have to expose preferrably private variables and methods publicly in order to be implemented. This would be a serious blow to the concepts of encapsulation and information hiding in Java.
Campbell Ritchie wrote:No, there is no restriction on access to private members between different instances of the same class. You know about it. You wrote the class knowing where there is access to private members of other instances.
SCJP 6, SCWCD 5, SCBCD 5
"ye shall know the truth & the truth shall set you free..."
sandeeep shinde wrote:
uj nossnahoj wrote:
The reason for this behavior is quite obvious if you think about it. Otherwise many (or even most) classes would have to expose preferrably private variables and methods publicly in order to be implemented. This would be a serious blow to the concepts of encapsulation and information hiding in Java.
Does this mean in general that there is no restriction on accessing data between instances of the same class?
Still I don't get the point. Could you please elaborate on this?
SCJP 6, SCWCD 5, SCBCD 5
uj nossnahoj wrote:
That's right, there's no restriction, and my point is that this is necessary. Otherwise many classes would be forced to expose implementation detail to the outside (by raising the access rights of variables and methods that better would stay private). And this would be contrary to encapsulation and information hiding.
sandeeep shinde wrote:
That is the point. Why would classes be forced to expose implementation detail if we put the restriction?
Every time you till, you lose 30% of your organic matter. But this tiny ad is durable:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
|