1In Java, access specifiers are the
2keywords which are used to define
3the access scope of the method, class, or a variable.
4 In Java, there are four access specifiers.
5
6 * Public: The classes, methods, or variables
7 which are defined as public,
8 can be accessed by any class or method.
9 * Protected: Protected can be accessed
10 by the class of the same package,
11or by the sub-class of this class, or within the same class.
12 * Default: Default are accessible
13 within the package only.
14 By default, all the classes, methods,
15and variables are of default scope.
16 * Private: The private class, methods,
17or variables defined as private
18 can be accessed within the class only
1Example of private access modifier:
2
3class Demo
4{
5 private void display()
6 {
7 System.out.println("Hello world java");
8 }
9}
10public class PrivateAccessModifierExample
11{
12 public static void main(String[] args)
13 {
14 Demo obj = new Demo();
15 System.out.println(obj.display());
16 }
17}
1In Java, access specifiers are the keywords which are used to define
2the access scope of the method, class, or a variable.
3 In Java, there are four access specifiers.
4
5 * Public: The classes, methods, or variables which are defined as public,
6 can be accessed by any class or method.
7 * Protected: Protected can be accessed by the class of the same package,
8or by the sub-class of this class, or within the same class.
9 * Default: Default are accessible within the package only.
10 By default, all the classes, methods, and variables are of default scope.
11 * Private: The private class, methods, or variables defined as private
12 can be accessed within the class only
1For top level class only two access modifiers are allowed.
2public and default. If a class is declared as public it is visible everywhere.
3If a class is declared default it is visible only in same package.
4If we try to give private and protected as access modifier to class
5we get the below compilation error.
6Illegal Modifier for the class only public,abstract and final are permitted.