• Post Reply Bookmark Topic Watch Topic
  • New Topic

accessing private from driver class  RSS feed

 
Kamesh Sai
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Experts,

I am begining to learn Java and i came accross the below

1) When a variables are declared "Private" How should it be accessed from the driver class ? Sometimes i get an error in driver class saying "your variable is declared Private" why am i getting this error (Sorry i do not have the code Handy)

The document says "Private" declared variables should be accessed only through methods. What does that mean.

Regards,
Sai
 
Knute Snortum
Sheriff
Posts: 4279
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Usually, a private variable that is allowed to be accessed has a "getter" method with the name "getVarname". There is one exception to this: if the variable is boolaen, the method is called "isVarname".

So if your private variable is named "foo", the getter would be "getFoo()".
 
Kamesh Sai
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks much Snortum.
 
Campbell Ritchie
Marshal
Posts: 56553
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason for using getXXX methods (or also setXXX methods) is that it allows the object control over its own state. If you don't give fields private access, you can write this sort of thing
myObject.number = -9999999;
… when number is supposed always to be positive. You can put tests in your setXXX methods to ensure incorrect values are excluded. In some cases, you need to take more stringent precautions, even copying any objects going into or coming out of your object. As you see in this old discussion, Joshua Bloch wrote about that in Effective Java™.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!