Explain how Access Specifiers are used to control access to Variables and Methods
Access modifiers in Java
Access modifiers are used to control access to a class, interface, constructor, variable, method, or inner class. Java supports the public, protected, and private access modifiers.
It also supports a default access, referred to as package access or friendly access, when no other modifier is specified.
Default or Package access: The default access that occurs when no access modifier is specified. Access is restricted to the package in which an item is declared. Also referred to as friendly access.
Pay attention to access modifiers. You are likely to see a few certification exam questions that will test your knowledge of them.
Public Access Modifier
A public class or interface is accessible outside of its package. A public variable, method, constructor, or inner class is accessible anywhere that the class may be accessed.
Top-level classes and interfaces may be declared as
default (no modifier)
access . Top-level classes may not be declared protected or private.
A protected variable, method, constructor, or inner class may be accessed in the package, class and subclasses of the class in which it is declared.
A private variable, method, constructor, or inner class may only be accessed in the class in which it is declared.
Package or default access
Package access is the default access when no other access modifier is specified.
An item that is declared with package access may only be accessed within the package it is declared.