標籤:
Access Levels
| Modifier |
Class |
Package |
Subclass |
World |
| public |
Y |
Y |
Y |
Y |
| protected |
Y |
Y |
Y |
N |
| no modifier |
Y |
Y |
N |
N |
| private |
Y |
N |
N |
N |
The following table shows where the members of the Alpha class are visible for each of the access modifiers that can be applied to them.
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
| Modifier |
Alpha |
Beta |
Alphasub |
Gamma |
| public |
Y |
Y |
Y |
Y |
| protected |
Y |
Y |
Y |
N |
| no modifier |
Y |
Y |
N |
N |
| private |
Y |
N |
N |
N |
原來我一直都弄反了
protected的可見度實際上是大於package的.實習面試的時候,我一直都說錯了。
Access Levels的實質
If you have a field that’s private it means no other class can get at it. Wrong! If you really want to you can subvert the access control mechanisms in almost any language. Usually the way through is via reflection. The rationale is that debuggers and other system tools often need to see private data , so usually the reflection interfaces allow you to do this.
C++ doesn’t have this kind of reflection, but there you can just use direct memory manipulation since C++ is fundamentally open memory.
The point of access control is not to prevent access, but more to signal that the class prefers to keep some things to itself. Using access modifiers, like so many things in programming, is primarily about communication.
http://martinfowler.com/bliki/AccessModifier.html
果然是專家,說出來的話太有水平了!
我理解的,存取控制實際是編譯時間有效,類似於宏定義一樣的東西,並不具備運行時檢查。
不知道這個理解是不是錯誤的。我暫時還沒找到去哪裡驗證這個觀點。希望有人能給出切實的說法。
來自為知筆記(Wiz)
Java Access Levels(存取控制)