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
// Public class public class MyClass { // Protected method protected void myProtectedMethod() { } // Default field int myDefaultField; // Private constructor private MyClass() { } }
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 inMyClass
itself as well as its subclasses.myDefaultField
is a default field that can only be used in classes in the same package asMyClass
. The constructor ofMyClass
is private and can only be used withinMyClass
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!