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

What are access modifiers in Java?

Susan Sarandon
Release: 2025-01-24 22:12:11
Original
379 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template