Java Programming/Access Modifiers
| Navigate Language Fundamentals topic: |
[edit] Access modifiers
You surely would have noticed by now, the words public, protected and private at the beginning of class's method declarations used in this book. These keywords are called the access modifiers in the Java language syntax, and can be defined as...
| “ | .. keywords that help set the visibility and accessibility of a class, its member variables, and methods. | ” |
The following table shows what Access Modifiers are appropriate for classes, nested classes, member variables, and methods:
| Class | Nested class | Method, or Member variable | Interface | Interface method signature | |
|---|---|---|---|---|---|
public |
visible from anywhere | same as its class | same as its class | visible from anywhere | visible from anywhere |
protected |
N/A | its class and its subclass | its class and its subclass, and from its package | N/A | N/A |
| package (default) | only from its package | only from its package | only from its package | N/A | N/A, default is public |
private |
N/A | only from its class | only from its class | N/A | N/A |
Note that Interface method visibility is
public by default. You do not need to specify the access modifier it will default to public. For clarity it is considered a good practice to put the public keyword.The same way all member variables defined in the Interface by default will become
static final once inherited in a class.If a class has public visibility, the class can be referenced by anywhere in the program. If a class has package visibility, the class can be referenced only in the package where the class is defined. If a class has private visibility, (it can happen only if the class is defined nested in an other class) the class can be accessed only in the outer class.
If a variable is defined in a public class and it has public visibility, the variable can be reference anywhere in the application through the class it is defined in. If a variable has package visibility, the variable can be referenced only in the same package through the class it is defined in. If a variable has private visibility, the variable can be accessed only in the class it is defined in.
If a method is defined in a public class and it has public visibility, the method can be called anywhere in the application through the class it is defined in. If a method has package visibility, the method can be called only in the same package through the class it is defined in. If a method has private visibility, the method can be called only in the class it is defined in.