File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Private variable problem" Watch "Private variable problem" New topic

Private variable problem

Joseph yan

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.


Paul Sturrock

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

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

Joined: Mar 09, 2009
Posts: 600

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.

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46410
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:
subject: Private variable problem
jQuery in Action, 3rd edition