Overhead of Using Inner Classes

Overhead of Using Inner Classes

An interesting situation with method call overhead arises when you use inner classes. The inner class specification says that a private method of a class A can be used by a class B, if A encloses B. That is, if B is a class defined within A, it can call A’s private methods. Here is an example:

 // methods and inner classespublic class meth_inner {        private void f() {}        class A {                A() {                        f();                }        }        public meth_inner() {                A a = new A();        }        public static void main(String args[]) {                meth_inner x = new meth_inner();        }}

A is an inner class defined within meth_inner, and A’s constructor calls a private method f() defined in meth_inner. Because the Java Virtual Machine has restrictions on calling private members from outside of their class, a special access method is generated by the compiler and added internally to the meth_inner class. This method has a name access$0(), and it in turns calls f(). In other words, a method is generated that can be called from outside of meth_inner, and grant access to a private method of meth_inner. So when f() is called above, a generated method access$0() is called, and it in turn calls f(). If you use the JDK utility program that disassembles .class files, by saying:

 $ javap -c meth_innerthe output includes the following method definition: Method void access$0(meth_inner)   0 aload_0   1 invokespecial #7    4 return

This is the body of the generated method. You can avoid this overhead by avoiding use of private members in a class, assuming the class has inner classes that use those members. Obviously, however, there may be other reasons why private members are more important than the overhead associated with these generated methods.

See also  The Benefits of Patient Engagement Solutions for Healthcare Providers

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist