Java Type of Access Modifiers
Access modifiers are used to control the visibility and accessibility of classes, methods and fields. By setting the appropriate access modifiers, you can ensure that your code is more secure, maintainable, and extensible.
Java has four types of access modifiers:
public
: Thepublic
modifier makes the class, method or field accessible from anywhere in the program.private
: Theprivate
modifier makes the class, method or field accessible only within the class it is declared in.protected
: Theprotected
modifier makes the class, method or field accessible within the same package or any subclasses outside the package.default
: If no access modifier is specified, it is known aspackage-private
ordefault
access. This means that the class, method or field is accessible only within the same package.
Here's an example of how the different access modifiers can be used for a class, its fields and methods:
public class MyClass { public int publicVar; // can be accessed from anywhere private int privateVar; // can only be accessed within this class protected int protectedVar; // can be accessed within this package and any subclasses outside the package int defaultVar; // can be accessed only within the same package public void publicMethod() { // can be accessed from anywhere // method body } private void privateMethod() { // can only be accessed within this class // method body } protected void protectedMethod() { // can be accessed within this package and any subclasses outside the package // method body } void defaultMethod() { // can be accessed only within the same package // method body } }