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.
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.
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