38.What are Access Specifiers?
One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. Java allows you to control access to classes, methods, and fields via so-called access specifiers..
39.What are Access Specifiers available in Java?
Java offers four access specifiers, listed below in decreasing accessibility:
- Public- public classes, methods, and fields can be accessed from everywhere.
- Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package.
- Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.
- Private- private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses.
Situation | public | protected | default | private |
---|---|---|---|---|
Accessible to class from same package? | yes | yes | yes | no |
Accessible to class from different package? | yes | no, unless it is a subclass | no | no |
EmoticonEmoticon