Access Modifiers in Java
Access Modifiers in Java specifies the level (or scope) of access to classes, variables, methods and constructors. There are four access modifiers in Java:
- Private
- Protected
- Default (no keyword is used)
- Public
Public Access Modifier:
Public means available to all. Public classes, methods, variables and constructors are accessible everywhere within the project.
Example:
Let us consider a class – ClassA which has two integer variables – firstNum and secondNum – both defined as public and a method addTwoNumbers(), again defined as public.
package accessModifiers; public class ClassA { public int firstNum; public int secondNum; public int addTwoNumbers(){ return firstNum + secondNum; } }
Another class with ClassB is defined in which a variable (instance) of ClassA is created and as the variables and methods defined in ClassA are public, all of them are accessible here. Refer below code:
package accessModifiers; public class ClassB { public static void main(String[] args) { ClassA a = new ClassA(); a.firstNum = 10; a.secondNum = 23; int sum = a.addTwoNumbers(); System.out.println("Sum :: "+ sum); } }
Let us look at another scenario where ClassA is extended by ClassC. Here also all the methods and variables which are public are accessible. Refer below code:
package accessModifiers; public class ClassC extends ClassA{ public void addNumbers(){ firstNum = 13; secondNum = 23; addTwoNumbers(); } }
Private Access Modifier:
Private methods and variables can be accessed within same class only. They are not accessible outside the class.
Protected Access Modifier:
Protected methods, variables and constructors can be accessed within the same package via both means (calling from the instance of a class or via Inheritance) but outside a package, they can be accessed only via Inheritance.
Note: Classes cannot be private or protected, they can only be public or default.
Default Access Modifier:
No keyword is used for default access modifier. Methods, variable and constructors can be accessed within the same package only via both ways (creating an instance of a class or via inheritance) but outside a package, it cannot be accessed via any means.