Java access modifiers control the visibility and accessibility of classes, methods, constructors, and data members. There are four access modifiers in Java:
public: Classes, methods and data members can be accessed from anywhere in the program.
<code class="language-java">public class MyClass { public void display() { System.out.println("Public method"); } }</code>
private: Data members can only be accessed within the same class in which they are declared, and cannot be accessed by other classes even within the same package.
<code class="language-java">public class MyClass { private int data = 10; private void display() { System.out.println("Private method"); } }</code>
protected: Data members and methods are accessible in the same package and subclasses.
<code class="language-java">public class MyClass { protected int data = 10; protected void display() { System.out.println("Protected method"); } }</code>
default (package access): If no keyword is specified, the default access modifier is applied, which makes the class, method or data member only accessible within the same package.
<code class="language-java">class MyClass { // default access void display() { // default access System.out.println("Default method"); } }</code>
Thanks for reading! Welcome to raise your questions and suggestions in the comment area and learn and make progress together!
The above is the detailed content of What are access modifiers in Java?. For more information, please follow other related articles on the PHP Chinese website!