
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
Demonstrate Private Access Modifier in Java
The data members and methods of a class can be accessed only from within their declared class if they are specified with the private access modifier. The keyword private is used to specify this modifier.
A program that demonstrates the private access modifier in Java is given as follows:
Example
class A { private int a = 6; public void printA() { System.out.println("Value of a = " + a); } } public class Demo { public static void main(String args[]) { A obj = new A(); obj.printA(); } }
Output
Value of a = 6
Now let us understand the above program.
The class A has a private data member a that can be accessed only from within the class. The method printA() displays the value of a. A code snippet which demonstrates this is as follows:
class A { private int a = 6; 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. 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.printA(); } }
Advertisements