Home> Java> javaTutorial> body text

What are the access modifiers in java

下次还敢
Release: 2024-05-01 18:09:16
Original
349 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

  • publicModifiers are used on classes, methods and fields to make them visible in all classes and packages visible. This is the broadest visibility.
  • protectedModifiers are typically used on methods and fields to allow subclasses to access them. This protects members from inappropriate access by other classes.
  • defaultmodifier is used implicitly when no other visibility modifier is explicitly specified. It restricts members to be visible to classes in the same package.
  • privateModifiers 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

// Public class public class MyClass { // Protected method protected void myProtectedMethod() { } // Default field int myDefaultField; // Private constructor private MyClass() { } }
Copy after login

In this example:

  • MyClassis a public class that can Used in any class or package.
  • myProtectedMethodis a protected method that can be used inMyClassitself as well as its subclasses.
  • myDefaultFieldis a default field that can only be used in classes in the same package asMyClass. The constructor of
  • MyClassis private and can only be used withinMyClassitself.

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 Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!