Revisit Access Specifiers
Access specifiers, also known as access modifiers, are keywords in Java that set the accessibility (visibility) of classes, interfaces, variables, methods, and other members. They define the scope and visibility of these components.
There are four types of access specifiers in Java:
Public: The
public
keyword is an access modifier that makes a member (class, interface, variable, method, etc.) accessible from anywhere. This means that a public member is visible to all classes in all packages.Private: The
private
keyword makes a member accessible only within the class in which it is declared. It is the most restrictive access level. So, variables, methods, and constructors that are declared private can't be accessed outside the class and are not visible to any other class, including subclasses.Protected: The
protected
keyword makes a member accessible within the same package and also to subclasses of the class in any package. So, if you have a variable, method, or constructor declared as protected, it can be accessed within the same class, by other classes in the same package, and by subclasses in other packages.Default (Package-Private): When no access specifier is specified, the member is treated as having "default" access, also known as "package-private". This means the member is accessible within the same class, and also by other classes in the same package, but not by classes in other packages or subclasses in other packages.
Access Modifier | Within Class | Within Package | Outside Package by subclass | Outside Package |
---|---|---|---|---|
Private | Yes | No | No | No |
Default | Yes | Yes | No | No |
Protected | Yes | Yes | Yes | No |
Public | Yes | Yes | Yes | Yes |
By controlling access, you can prevent misuse. For example, with the private
modifier, you can hide data from users of your class and allow access only through methods that you control. This concept is also known as data encapsulation or data hiding.
COSC-1437 / ITSE-2457 Computer Science Dept. - Author: Dr. Kevin Roark