Inner Classes Change Access Rights Of Parent Members?!?

C

cppaddict

I read that if you access a parent class's private memebers or methods
from within an inner class, those members of methods will
automatically and silently be converted to having package access. This
seems dangerous and I'd like to know how I could design around it.

Here is my current dilemma. I have an EventHandler class whose
handleEvent() method changes with the object's state. I've implemented
this using the Strategy Pattern, where the Strategy objects are inner
classes of EventHandler. The problem is that these Strategy objects
need access to certain private members and methods of their parent.
There is no reason, however, to give package access to these members
and methods. What can I do? Or does this suggest that I need a design
change? Other than this issue, though, I'm quite happy with the
design.

Thanks for any thoughts,
cpp
 
C

cppaddict

I found a good answer for this somewhere else:

When inner classes access private fields or methods, the compiler
generates new package-private methods
with names like "access$000":

<code>
import java.lang.reflect.*;
public class Test {
private void x() {
}
class Y {
public void y() {
x();
}
}
public static void main(String[] args) {
Method[] methods = Test.class.getDeclaredMethods();
for(int i=0; i<methods.length; ++i)
System.out.println(methods.getName());
}
}
</code>

So it's not correct that the access to fields or methods is changed,
just that additional methods are added. Unless you're in the habit of
writing method names that contain '$', I think it's unlikely that
you'll directly call these new methods, and if you do, it should be
easy to spot!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top