Nest-based access control

Imagine what happens when you define nested classes or interfaces? For instance, if you define a two-level class, say Outer, and an inner class, say Inner, can Inner access the private instance variables of Outer? Here's some sample code:

public class Outer { 
    private int outerInt = 20; 
    public class Inner { 
        int innerInt = outerInt;     // Can Inner access outerInt? 
    } 
} 

Yes, it can. Since you define these classes within the same source code file, you might assume it to be obvious. However, it is not. The compiler generates separate bytecode files (.class) for the Outer and Inner classes. For the preceding example, the compiler creates two bytecode files: Outer.class and Outer$Inner.class. For your quick reference, the bytecode file of an inner class is preceded by the name of its outer class and a dollar sign.

To enable the access of variables across these classes and to preserve the expectations of programmers, the compiler broadens the access of private members to a package or adds bridge variables or methods in each of these classes. Here's the decompiled version of the Outer and Inner classes that have been decompiled using the JAD Java Decompiler:

// Decompiled class Outer 
public class Outer { 
    public class Inner { 
        int innerInt; 
        final Outer this$0; 
 
        public Inner() { 
            this$0 = Outer.this; 
            super(); 
            innerInt = outerInt; 
        } 
    } 
    public Outer() { 
        outerInt = 20; 
    } 
    private int outerInt; 
} 

And here is the Outer$Inner decompiled class, as follows:

public class Outer$Inner { 
    int innerInt; 
    final Outer this$0; 
 
    public Outer$Inner() { 
        this$0 = Outer.this; 
        super(); 
        innerInt = outerInt; 
    } 
}

As you will notice, the decompiled versions verify that the compiler defined a bridge variable, that is, this$0 of type Outer in the Inner class, to access members of Outer from Inner.

These bridge variables and methods risk encapsulation and increase the size of the deployed application. They can also confuse developers and tools.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.140.204