- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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(); } }
- Related Articles
- protected access modifier in Java
- Protected vs Final Access Modifier in Java
- What is the scope of protected access modifier in Java?
- private access modifier in Java
- default access modifier in Java
- public access modifier in Java
- Can we declare main() method as private or protected or with no access modifier in java?
- Demonstrate Private access modifier in Java
- Protected vs Package Access Modifiers in Java
- Public vs Protected Access Modifiers in Java
- WiFi Protected Access (WPA) and WiFi Protected Access 2 (WPA2)
- What is the scope of public access modifier in Java?
- What is the scope of default access modifier in Java?
- What is the scope of private access modifier in Java?
- Wifi protected access (WPA)
