Home > Java > javaTutorial > What are the access modifiers in java

What are the access modifiers in java

下次还敢
Release: 2024-05-01 18:09:16
Original
474 people have browsed it

Access modifiers in Java control member visibility, there are four: public (all classes and packages), protected (same package and subclasses), default (same package) and private (only declared classes) .

What are the access modifiers in java

Access modifiers in Java

In Java, access modifiers are used to control classes, methods, Visibility of fields and other members. There are four access modifiers, which are:

  • public: Members are visible in all classes and packages.
  • protected: Members are visible in the same package and in subclasses.
  • default (or package access): Members are visible in the same package.
  • private: Members are only visible within the class in which they are declared.

Usage

  • public Modifiers are used on classes, methods and fields to make them visible in all classes and packages visible. This is the broadest visibility.
  • protected Modifiers are typically used on methods and fields to allow subclasses to access them. This protects members from inappropriate access by other classes.
  • default modifier is used implicitly when no other visibility modifier is explicitly specified. It restricts members to be visible to classes in the same package.
  • private Modifiers are used on methods and fields that can only be accessed within the class in which they are declared. This visibility provides the strictest access control.

Example

<code class="java">// Public class
public class MyClass {

    // Protected method
    protected void myProtectedMethod() { }

    // Default field
    int myDefaultField;

    // Private constructor
    private MyClass() { }
}</code>
Copy after login

In this example:

  • MyClass is a public class that can Used in any class or package.
  • myProtectedMethod is a protected method that can be used in MyClass itself as well as its subclasses.
  • myDefaultField is a default field that can only be used in classes in the same package as MyClass. The constructor of
  • MyClass is private and can only be used within MyClass itself.

The above is the detailed content of What are the 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