Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why this private member can be seen?

 
Qunfeng Wang
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Why a.num can be seen here? What does the private mean?
 
Keith Pitty
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The keyword private indicates that a member is private to that class.

So in the contrived example where you have a constructor of the form public MyClass(MyClass myObj), it is indeed valid to refer to private members of myObj directly.

Why? Because the object reference being passed in is of the type that is being constructed. The code is all there in the class.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With other words, private doesn't restrict access to the object, but to the class.

This makes sense when you think about what access modifiers are good for: managing code dependencies.
 
Qunfeng Wang
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

private doesn't restrict access to the object, but to the class.

The a.num can be seen just because a appears in class A.
a is an object of class A, private members can be seen in the class, so a.num can be seen in A. Can I catch you meaning?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I think you got it!
 
Qunfeng Wang
Ranch Hand
Posts: 434
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your answer.
Another question come up:
Why this constructor? It has some special useage?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic