Java Access Specifiers

Java Access Specifiers
Access specifier defines the boundary and scope to access the method, variable, and class etc.
Java has defines four type of access specifiers such as:-
1. public
2. private
3. protected
4. default / friendly
These access specifiers are defines the scope for variables/methods. If you are not defining any
access specifier so it will be as 'default' access specifier for variables/methods.
1. public access specifier:- If you declare any variable/ function as public access specifier so you
can used it from anywhere of the program.
Syntax:-
< Access Specifier >     data type variable /function ;
Ex:-
public int number;
2. private access specifier:- If you declare any variable/ function as private access specifier so you
can used within the java class itself, not from outside the class, package and others.
Syntax:-
< Access Specifier >     data type variable / function;
Ex:-
private int number=10;
3. protected access specifier:- If you want to access the private variable of parent class within your
child class so you can declare those variable as protected. If your variable/method is declared as
protected so that variables/methods can be access same Class name, Package name, and sub class.
Syntax:-
< Access Specifier >     data type variable / function;
Ex:-
protected int number=10;
4. default access specifier:- Actually, there is no default access modifier; the absence of a modifier is
treated as default. A method or variable, declared default( that is, no access modifier specified at all ),
can be accessed by any class belonging to the same package.
Classes belonging to other packages cannot access. That is why default access modifier is known as
package level access.
A class can be either default or public.

Note: default is keyword and is used with switch statements.

No comments:

Post a Comment