Wednesday 26 September 2018

What is the difference between public, protected, package-private and private in Java?




In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), public, protected and private, while making class and interface and dealing with inheritance?


Answer



The official tutorial may be of some use to you.




______________________________________________________________
| │ Class │ Package │ Subclass │ Subclass │ World |
| │ │ │(same pkg)│(diff pkg)│ |
|───────────┼───────┼─────────┼──────────┼──────────┼────────|

|public │ + │ + │ + │ + │ + |
|───────────┼───────┼─────────┼──────────┼──────────┼────────|
|protected │ + │ + │ + │ + │ |
|───────────┼───────┼─────────┼──────────┼──────────┼────────|
|no modifier│ + │ + │ + │ │ |
|───────────┼───────┼─────────┼──────────┼──────────┼────────|
|private │ + │ │ │ │ |
|___________|_______|_________|__________|__________|________|
+ : accessible blank : not accessible


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...