Java Program to Access private members of a class

To understand this example, you should have the knowledge of the following Java programming topics:


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() and setName() initializes the private variables
  • the getter methods getAge() and getName() 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.