Home >Java >javaTutorial >How to use private in java
Private modifier is used in Java to restrict the visibility of members (fields, methods and inner classes) so that they are only visible within the class in which they are defined. It is used for information hiding, encapsulation and data integrity. Private members are only accessible within the class in which they are declared; subclasses and classes in other packages cannot access them. Exceptions are access via getter/setter methods or the reflection API.
Usage of private in Java
In the Java programming language, private
is An access modifier that limits the visibility of members (fields, methods, and inner classes) in a class or interface so that they are only visible within the class in which they are defined.
Uses:
private
Modifiers are mainly used for the following purposes:
Syntax:
When using the private
keyword to declare class members, the syntax is as follows:
<code class="java">private <成员类型> <成员名称>;</code>
For example:
<code class="java">private int age; private String name;</code>
Visibility rules:
Exception:
In some cases, private members can also be accessed in other classes, for example:
getter
or setter
method. When to use:
Generally, when the following conditions are met, you should use private
Modifier:
The above is the detailed content of How to use private in java. For more information, please follow other related articles on the PHP Chinese website!