This tutorials explains the various access modifiers used in Java language and the scope for the each modifier. There is four types of access modifiers in Java.
- private
- default
- protected
- public
Private Modifier
If you declare anything private inside a class, then it must be accessed inside that class. Other classes can not access that variables or methods directly.
- We can not declare a class as private
- Variables and methods can be declared as private.
- If you declare a constructor as private, we can not create instance using that constructor.
- Private is the least access modifier.
[code lang=”java”]
package javabeat.net.core;
public class SuperClass {
private int i;
private SuperClass(){
//Private constructor
}
private void method(){
//Private method
}
}
[/code]
Default Modifier
If you don’t declare access modifier, then it is considered as the default access. It means that the access is granted within the same package.
- Default access has no keyword. Without any access modifier is considered as default access.
- This access is applicable for classes, methods and variables.
[code lang=”java”]
package javabeat.net.core;
public class SuperClass {
int i;
SuperClass(){
//Default constructor
}
void method(){
//Default method
}
}
package javabeat.net.core;
public class OtherClass {
void method(){
SuperClass class1 = new SuperClass();
System.out.println(class1.i);
}
}
[/code]
Protected Modifier
If you declare a method or variable as the protected, it can be accessed within the same package and sub classes in the other packages.
- Classes can not be declared as protected access.
- Variables and methods can be declared as protected.
- The main purpose of the protected is to give access for its sub classes.
[code lang=”java”]
package javabeat.net.core;
public class SuperClass {
protected int i;
protected SuperClass(){
//protected constructor
}
protected void method(){
//protected method
}
}
package javabeat.net.core;
public class SubClass extends SuperClass{
protected void method (){
SuperClass class1 = new SuperClass();
System.out.println(class1.i);
}
}
[/code]
Public Modifier
If you declare as public, then the data member can be accessed from anywhere .
- Classes, variables and methods can be public.
- It is the maximum access level
Summary of Access Level
Modifier | Inside Class | Inside Package | Other Package by Subclass Only | Other Package |
---|---|---|---|---|
Private | Y | N | N | N |
Default | Y | Y | N | N |
Protected | Y | Y | Y | N |
Public | Y | Y | Y | Y |
Leave a Reply