Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why Protected access modifier used in Java?
The data members and methods of a class can be accessed from the same package or sub-classes in a different package if they are specified with the protected access modifier. The keyword protected is used to specify this modifier.
A program that demonstrates the protected access modifier in Java is given as follows:
Example
class A {
protected int a = 9;
public void printA() {
System.out.println("Value of a = " + a);
}
}
public class Demo {
public static void main(String args[]) {
A obj = new A();
obj.a = 18;
obj.printA();
}
}
Output
Value of a = 18
Now let us understand the above program.
The class A has a protected data member a that can be accessed from the same package or sub-classes in a different package. The public method printA() displays the value of a. A code snippet which demonstrates this is as follows:
class A {
protected int a = 9;
public void printA() {
System.out.println("Value of a = " + a);
}
}
In the main() method in class Demo, an object obj of class A is created. The value of obj.a is modified which is possible as it is protected and the modification is done in the same package. Then printA() method is called. A code snippet which demonstrates this is as follows:
public class Demo {
public static void main(String args[]) {
A obj = new A();
obj.a = 18;
obj.printA();
}
}