wood burning stoves*
The moose likes Servlets and the fly likes what is the concept of private variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "what is the concept of private variable" Watch "what is the concept of private variable" New topic

what is the concept of private variable

sudhakar kandasamy

Joined: Dec 09, 2007
Posts: 4
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

Joined: Jan 07, 1999
Posts: 6920
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.

Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
yoginee Pathak

Joined: Apr 25, 2001
Posts: 3
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
subject: what is the concept of private variable