Inner Classes Change Access Rights Of Parent Members?!?

Discussion in 'Java' started by cppaddict, Aug 23, 2004.

  1. cppaddict

    cppaddict Guest

    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
     
    cppaddict, Aug 23, 2004
    #1
    1. Advertising

  2. cppaddict

    cppaddict Guest

    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!
     
    cppaddict, Aug 23, 2004
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. lonelyplanet999
    Replies:
    1
    Views:
    2,252
    VisionSet
    Nov 13, 2003
  2. Christian Bongiorno
    Replies:
    5
    Views:
    555
    Chris Uppal
    Aug 30, 2004
  3. Wolfgang Jeltsch
    Replies:
    7
    Views:
    428
    Josephine Schafer
    Aug 15, 2003
  4. Carlo v. Dango
    Replies:
    14
    Views:
    1,066
    Alex Martelli
    Oct 19, 2003
  5. Pyenos
    Replies:
    2
    Views:
    400
    Pyenos
    Dec 27, 2006
Loading...

Share This Page