Example 1: Access private fields using getter and setter methods
Output
Age: 24 Name: nodmek
In the above example, we have private variables named age and name. Here, we are trying to access the private variables from other class named Main.
We have used the getter and setter method to access the private variables. Here,
- the setter methods
setAge()andsetName()initializes the private variables - the getter methods
getAge()andgetName()returns the value of private variables
Example 2: Access the private field and method using Reflection
Output
Name: nodmek Method Name: display Access Modifier: private
In this example, we have a private field named name and a private method named display(). Here, we are using the reflection to access the private fields and methods of the class Test.
To learn about reflection, visit Java Reflection.