It is something that controls the visibility and accessibility of class, methods, and variables.
Purpose of Access Specifiers?
Types & explanation for each?
Private:
private variable: inside the class
private method: other methods inside the class can call any of the private method.
you cannot define the access specifier to be private : for a class
class ABC{
private class XYZ{
function();
}
}
//
public void update() {
XYZ obj = new XYZ();
obj.function();
}
public
Note: If a class doesn’t have an access specifier : it is package-private by default.
/* If it is package private :
outsite the package you will not be able to create an object
and if you are not able to create an object
you will not be able to access the name */
class Account { // this would be package-private
public string name;
}
/*
folder name
- abc.java
- xyz.java
*/
Protected. : inside the package & to the subclass of the package 1.
// Package 1
protected class ABC{
}
class XYZ extends ABC{
method(){
ABC obj = new ABC();
obj.name =
/* Because it is a private class: we were able to access it.
// Package 2
protected class DEF{
method(){
ABC obj = new ABC()
}
}
Package Private : (it is the default) 1.
class Account {// this is package private
}
| class | package | subclass | world | |
|---|---|---|---|---|
| public | yes | yes | yes | yes |
| protected | yes | yes | yes | no |
| default | yes | yes | no | no |
| private | yes | no | no | no |