• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why can I access this private property directly?

 
Jack McGuire
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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.
 
Jack McGuire
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Matthew Brown
Bartender
Posts: 4565
8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's right. It's restricted to the class, not the object.
 
Jack McGuire
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks! :-)
 
Detlef Boehm
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
gurpeet singh
Ranch Hand
Posts: 924
1
Fedora Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic