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) .
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:
Usage
Example
<code class="java">// Public class public class MyClass { // Protected method protected void myProtectedMethod() { } // Default field int myDefaultField; // Private constructor private MyClass() { } }</code>
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!