Monday, June 16, 2008

Why Java needs Inner Classes?


Why Java needs Inner Classes?

Though there are various other uses of Inner Classes as well, but there is one scenario where it seems that it's the only practical solution. This is the scenario where we need a construct like 'method pointers' in C/C++. We may need a block of code to be referenced without having a handle to the object or class that block is a part of.

This can be implemented in Java by implementing the 'callback' approach using Inner Classes. This is implemented typically by wrapping the code in an adapter class and this class is made to implement the required interface. These adapter classes are implemented using inner classes and since these are classes having multiple entry points - they provide better flexibility as compared to what a programmer achieves by using function pointers in C/C++.

Another benefit of this approach is that it's simpler than the function pointer approach and it keeps the runtime environment stable. The adapter classes implemented using inner classes normally improve performance as well as they can be optimized to greater extent than their top-level adapter counterparts.

Other common uses of Inner Classes include:-

Providing alternate interface to an existing class - we simply add another method with the return type as the new interface and return the object of that type by using anonymous inner classes.

class ExistingClass implements someInterface{
...
...
public AlternateInterface getAlternateType(){
return new AlternateInterface() {
//...implementation of the alternate interface
...
...
};
}
...
}

Implementing custom Enumerations - the implementation will look quite similar to the above implementation. We use anonymous inner classes to implement and return custom Enumerations.

Accessing local final variables - local inner classes and anonymous inner classes can be used to access local final variables of the block of code they are defined into, which is typically a method.

Adding behavior to GUI - another distinguished usage scenario is the one where we anonymous inner classes for adding behavior to GUI components. These components already have their names and what all they need is the addition of a specific behavior and anonymous inner classes fittingly do that. Following any other approach for implementing this scenario makes the code clumsy and lengthy. Read more about the uses of Nested Classes in Java, their potential disadvantages, etc. in this article - Why do we need Nested Classes in Java?



Share/Save/Bookmark


No comments: