• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Private variable problem

 
Joseph yan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will need to change A to provide access either by making the variable protected or by adding an accessor method e.g. :
 
Vivek Singh
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use getters & setters to access that variable.
 
Joseph yan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48382
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic