Types of access specifiers in java: –Access specifiers also known as access modifiers in java, there are four types of access specifiers in java.
Types of access specifiers
- private
- protected
- default
- public
private access specifier in java example
If you make a variable or method private then it can be accessed only in the same class but can not be accessed outside the class.
private access specifier Example
- Same Class
public class A {
private int x=10;
private void test() {
System.out.println(100);
}
public static void main(String[] args) {
A a1 = new A();
a1.test();
System.out.println(a1.x);
}
}
output :
100
10
2. Same Package & subclass
Package p1;
public class A {
private int x=10;
private void test() {
System.out.println(100);
}
}
Package p1;
public class B extends A{
public static void main(String[] args) {
B b1 = new B();
b1.test(); // Error
}
}
You Also Learn –
- What is Abstract Class in Java
- What is Lambda Expression in Java 8
- What is Exception Handling in Java
- Types of Exceptions in Java
- What is inheritance in Java
- What is Final Keyword in Java
- What is Interface in Java
- What is Wrapper Class in Java
- Break Keyword in Java with Example
- What is Method In Java With Example
- What is Constructor in Java With Example
- What is Polymorphism in java
- What is non-static variable in java
3. Same Package & Non-subclass
Package p1;
public class A {
private int x=10;
private void test() {
System.out.println(100);
}
}
Package p1;
public class B {
public static void main(String[] args) {
A a1 = new A();
a1.test(); // Error
System.out.println(a1.x); //Error
}
}
4. Different Package & subclass
Package p1;
public class A {
private int x=10;
private void test() {
System.out.println(100);
}
}
Package p2;
Import p1.A;
public class B extends A {
public static void main(String[] args) {
B b1 = new B();
b1.test(); // Error
System.out.println(b1.x); //Error
}
}
5. Different Package & Non-subclass
Package p1;
public class A {
private int x=10;
private void test() {
System.out.println(100);
}
}
Package p2;
Import p1.A;
public class B {
public static void main(String[] args) {
A b1 = new A();
a1.test(); // Error
System.out.println(a1.x); //Error
}
}