0

I was going through an article regarding private access specifier , when to use private and what benefits does it offers in terms of encapsulation at the following url Regarding private access specifier

But there is one thing that was not clear in this article regarding accessing the private variable outside the class..Though private methods or variables are not accessible outside of Class, they can be accessed via reflection by using setAccessible(true) and changing there private visibility.

could you please show me a small example so that i can understand technically also.

1 Answers1

0

"private" members of a class can be accessed within the program only and that too with its own objects. Even inherited classes in the same package cannot access by composition. Observe the code. private variable can be accessed from the same class methods.

class Test
{
private int x = 10;
public void display()
{
       System.out.println(x);
}
}
public class Demo extends Test
{
public static void main(String args[])
{
   Demo d1 = new Demo();
   System.out.println(d1.x);   // error

   Test t1 = new Test();
   System.out.println(t1.x);   // error , it is composition (has-a relationship)     
   t1.display();                       // this works
}
}

I searched the web for this answer. I found in way2java.com in the topic Public methods and Private Variables