Forums Register Login

Why can I access this private property directly?

+Pie Number of slices to send: Send
Hi!

From page 546 on the SCJP Study Guide. I seem to be able to access the private property "moofValue" directly in the equals method without having to HAVE TO use the getMoofValue() getter method. Why is this?

Thanks for your help.

+Pie Number of slices to send: Send
"private" means "accessible only from within the same class". In this example you're accessing it from within the Moof class, so there's no restriction.
+Pie Number of slices to send: Send
Hey Matthew.

This means, I guess, that even when the object involved is not the "this" object, but is an argument object "Moof o" that is passed into the equals method, you can still access the argument "Moof o"s properties directly as we are "inside" the Moof class.

Is that the correct thinking here?
1
+Pie Number of slices to send: Send
That's right. It's restricted to the class, not the object.
+Pie Number of slices to send: Send
Thanks! :-)
+Pie Number of slices to send: Send
Hi Jack, hi others,
isn't it also, because the overridden equals() method is public!? And it has to be public, regarding the rules for overriding.

Best regards
Det
+Pie Number of slices to send: Send
Hi Detlef. Welcome to the Ranch!

Detlef Boehm wrote:isn't it also, because the overridden equals() method is public!? And it has to be public, regarding the rules for overriding.


No, it's nothing to do with that. You're right that the equals() method has to be public because it's overriding a public method; but the visibility of the method doesn't affect what the code inside that method can access, it only affects whether other code can access that method.
+Pie Number of slices to send: Send
 

Detlef Boehm wrote:Hi Jack, hi others,
isn't it also, because the overridden equals() method is public!? And it has to be public, regarding the rules for overriding.

Best regards
Det



no. private members are accessible from within the class. a method may be public, protected or private, if it is in the same class it can access private members of its class
LOOK! OVER THERE! (yoink) your tiny ad is now my tiny ad.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 881 times.
Similar Threads
Want hepl to understand Implementin an equals()
instance of problem
instanceof
doubt in equals method parameter
Not able to understand the program
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 09:11:49.