Home >Java >javaTutorial >What are access modifiers in Java?

What are access modifiers in Java?

Susan Sarandon
Susan SarandonOriginal
2025-01-24 22:12:11384browse

What are access modifiers in Java?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn