Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what is the concept of private variable

 
sudhakar kandasamy
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I declare a variable i as private.so derived class cannot access this i value,but if i create a public method getvalue which returns i value,through this method derived class can access this
private variable.Then where is the security for this private variavble.
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The point of a private variable is that you can only get it by calling a method. This means that the class is free to change the way it stores the information, without hurting other classes. Imagine we have a class:


and another class uses it like:

We now can't change the internal representation of the url. But what if we need to separate it out into the protocol (http) and the address (www,javaranch.com/)?
Imagine we had written it as:

It is now easy to change T1, without needing any changes to the other code:

This approach of "decoupling" the implementation of a class from its use is immensly useful in making code more maintainable. I've written hundreds of thousands of lines of Java, and I rarely use anything other than "private" for data members of classes.
 
yoginee Pathak
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi !
What Frank has said is absolutely right !
In short, private variables are accessible only to the methods in a class.
If you have done some C programming, you know if you declare a variable it is accessible throughout the program.
Read the concept of "encapsulation" carefully and i guess it should solve your problem
Yoginee
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic