Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Jul 6, 2000

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 classes
public 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_inner
the 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.
C.V. Ram
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date