Friday, January 15, 2010

Java amazing things

I've come across with the very interesting thing in Java language.
Example below illustrates that.


public class PublicClass {

    private int mPrivateValue;

    public void privateMethod() {
        InnerClass inner = new InnerClass();
        // access to the private field of inner class
        inner.mPrivateValue = 7;
    }

    private class InnerClass {

        private int mPrivateValue;

        private void privateMethod() {
            // access to the private field of parent class
            PublicClass.this.mPrivateValue = 5;
        }
    }
}


In few words about the amazing thing:
1. Parent class have access to the private fields on inner class.
2. Inner class have access to the private fields of parent class.

Because parent and inner classes have implicit links to each other.

No comments:

Post a Comment