File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Private variable problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Private variable problem" Watch "Private variable problem" New topic
Author

Private variable problem

Joseph yan
Greenhorn

Joined: Mar 02, 2009
Posts: 3
Hi All,

I want to access a varible form my super class. But i am having problem to access that.

Below is my code :

If i declare varible as 'Private' then i am not able to access it but when i declare it as 'Protected' then it is accesible.

I dont want to break the encapsulation.

How can i access it when it is declared as Private.

am i undersatnding correct it or i am doing something wrong ?

Please shed some light on it.

Thanks
Joseph



Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

You will need to change A to provide access either by making the variable protected or by adding an accessor method e.g. :


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Vivek Singh
Ranch Hand

Joined: Oct 27, 2009
Posts: 92
You can use getters & setters to access that variable.
Joseph yan
Greenhorn

Joined: Mar 02, 2009
Posts: 3

Thanks for your replies ..

How do i do with getter and setter ?

Can you please provide some example .

Please note only problem is i dont want to break encapsulation.

if i will use protected then varible is visible out side the class.



John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Joseph:

You probably just want a getter. Just move your getPrice() method from class A to class B. Extending classes already breaks encapsulation. If encapsulation is what you are concerned about, you should probably use composition rather than inheritance.

John.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38472
    
  23
Joseph yan wrote:How do i do with getter and setter ?

Can you please provide some example .
Paul Sturrock has provided an excellent example which maintains encapsulation.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Private variable problem