• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

subclass calling private variable

 
Kevin P Smith
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simple question.

Is there an easy way round a subclass calling a PRIVATE variable from it's superclass?

The superclass is from a OOB system and I am not allowed to change it (hence the need for the subclass) but to run the subclass I need to call some variables (mainly a boolean) from the superclass.

Is there a way round it?

Cheers

KS
 
Campbell Ritchie
Sheriff
Posts: 48382
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The short answer is, no.

The long answer is, if they intended to allow access from subclasses they should provide public get and set methods, or some other method allowing users to alter the values.

BTW: Please don't use abbreviations like OOB whihc aren't familiar to users, especially not on the beginners' forum.
 
Rob Spoor
Sheriff
Pie
Posts: 20494
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The correct short answer is no, except through some hacks. Unless prevented by the security manager, reflection allows you to do such things.

Keep one thing in mind though: there is most likely a reason the fields are private, and if there are no public or protected methods to change them, you basically should not touch them. You will more likely break tested and proven behaviour of the base class than "fix" it for your own purposes.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rob Prime:

Keep one thing in mind though: there is most likely a reason the fields are private, and if there are no public or protected methods to change them, you basically should not touch them. You will more likely break tested and proven behaviour of the base class than "fix" it for your own purposes.


True.

On the other hand, there really *are* very rare situations where you really *need* access to something private, there simply is no other way using the provided API *and* there really is no better other way to work around the limitation. I've done this once or twice in my career, always felt uneasy about it, but still think that it was the best I could do in that situation.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic