|By Lawrence Rodrigues||
|April 1, 1997 12:00 AM EST||
In JDK 1.1, no other new feature is likely to have more impact on Java programmers than the less-publicized inner classes feature. It'll change the way in which Java programs have been traditionally written. The primary goal of this feature is to provide the ability to declare classes within classes.
To incorporate the new inner classes syntax and scope rules, a few significant changes were made to the Java language specifications. However, no changes were made to the Java Virtual Machine. This is because the new compiler implements the inner classes syntax using Java 1.0, which has no inner classes. As a result, binary compatibility is still maintained with Java programs written in Java 1.0.
The inner classes syntax is somewhat complicated. This article will provide an informal introduction to the syntax and discuss how inner classes can be used. As a case study, the author converted an existing application to JDK 1.1 using inner classes. This application was originally developed for the article on Image Loading (JDJ Vol 1, Issue 3). See Figure 1.
Need for Inner Classes
You can always write Java programs without using inner classes. So, is this feature really needed?. We'll address this question through an example shown in Listings 1 and 2. Such situations typically occur in GUI programming.
Listing 1 shows a simplified version of code that implements the GUI for the application shown in Figure 1. The outer-most ImageViewer class needs the CommandPanel class to create the GUI. The CommandPanel class needs the DisplayCommand class to handle the dispBtn events. As you can see from the code, the ImageViewer object is passed as an argument to the CommandPanel class and the CommandPanel object is passed as an argument to the DisplayCommand class. This is done in order for the actionPerformed method to invoke the displayImage method in the ImageViewer.
Let's suppose we can declare the CommandPanel class within the ImageViewer class as shown in Listing 2. Similarly, the DisplayCommand class is within the CommandPanel class. The CommandPanel class can then be considered a member of the ImageViewer class. In the same way, the DisplayCommand class can be considered as a member of the CommandPanel class. It is evident from the example that there is no need to pass the calling class as an argument to the called class. Furthermore, by placing the CommandPanel class and the DisplayCommand class close to where they are used, readability is considerably improved.
Using inner classes, we can declare classes within the body of another class just as in Listing 2. Whether it is the handling of events or developing huge applications, inner classes can result in compact Java programs and improved readability.
Furthermore, the lack of pointers in Java is strongly felt in applications that need to employ asynchronous operations such as callbacks. Event handling is a form of callback. A variation of inner class, called anonymous classes, allows the declaration of a class itself to be passed as an argument to a method. For example, the entire body of the DisplayCommand class can be passed as an argument to the addActionListener method. Such capabilities would make the implementation of callbacks simple, concise and elegant.
In order to explain the inner classes syntax and terms, we'll use the contrived example shown in Listing 3. This example has a number of classes, each having at least one method that prints the name of the class.
Nesting of Classes
The inner classes feature allows classes to be nested. A nested class is always surrounded by another class. We'll call such a class the enclosing class. An inner class can have as many enclosing classes as there are levels of nesting. In a package, there will always be classes that do not have an enclosing class. We'll call such classes as top-most1 classes. A top-most class is a member of the package to which it belongs. In the Image Viewer example, the ImageViewer class is the top-most class. Classes defined using JDK 1.0 are all top-most classes and we know from the Java language specifications that such classes cannot be declared static.
The inner classes feature allows a class to be declared as a member of another class. Therefore, a class that is a member of the top-most class can be declared static. With the new language specifications, a top-most class can have both static and non-static classes as its members. With this in mind, we'll define two types of member classes: inner classes and top-level classes.
According to the inner classes specifications, two types of classes can be called as top-level classes.
1. A top-most class; i.e., a class that is not enclosed by any other class
2. A static member of another top-level class
Alternatively, a top-level class can be defined as one that cannot directly access instance variables of other classes. In Listing 3, the OuterMost class is a top-level class, as are the StaticNestedOne and StaticNestedTwo classes. As we can see from this example, the static top-level classes can also be nested.
According to the inner classes specifications, the following three types of classes are qualified to be called as inner classes.
1. A class that is declared as a non-static member of another class. We'll define such classes as member inner classes1. It is declared within the class body, but outside a block. In Listing 2, the CommandPanel class and the DisplayCommand class are the member inner classes of ImageViewer. In Listing 3, InnerOne and InnerTwo are the member inner classes of the OuterMost class.
2. A class declared within a block. Such classes are defined as local classes.
3. A class embedded in an expression. In such cases, inner classes do not require a name or constructor. Such classes are defined as anonymous classes.
An inner class itself can have non-static classes nested declared within its body. In Listing 3, InnerNestedOne is nested within InnerOne.
Interfaces also can be declared as inner classes. Unlike inner classes, inner interfaces can have a static final variable declared in them. In Listing 3, the IDPrinter interface is declared within the InnerOne class and it has a static final variable.
Member Inner Classes
In this section, we'll discuss different aspects of member inner classes.
As per the inner classes specifications, an inner class can not have the same name as its enclosing classes. Furthermore, its name can not be the same as the name of the package to which it belongs.
Just like the other members of a class, a member inner class can be declared with the following access modifiers: private, protected and public. If the no access modifier is associated with a class, the visibility is package. Inner classes can also be abstract or final. As per the definition of inner classes, neither the inner class nor it's members can be declared static.
Accessing Inner Class Members
Members of an inner class include non-static variables, methods and classes. Except for members with private scope, inner class members can be accessed/used by enclosing classes. With appropriate access modifiers, they can also be accessed/used by other classes within or outside the package.
In order to access or use an inner-class member, an enclosing class related qualifier is always required. When the inner-class member is a class, it is referred to as
Accessing Enclosing Class Members
Members of the enclosing classes can be accessed/used from its inner classes with or without explicit qualifiers.
An inner class can directly access an enclosing class variable irrespective of its access modifier. Similarly, an inner class can use a class member of the enclosing class to create objects or for subclassing purposes. Just like variables, an inner class can use the class members in the enclosing scope irrespective of their access modifiers. In Listing 3, the printAllClasses method in the InnerNestedOne class uses a private class called InnerTwo in the enclosing scope to create an object and print its name.
Unlike variables and classes, inner classes cannot use the private methods in the enclosing scope. Trying to access private methods will result in compile-time error. But methods with protected, package and public scope can be used inside an inner class without any explicit qualifiers.
If an inner class or its super classes have a member which bears the same name/signature as the one in the enclosing scope, the enclosing name is hidden. In such cases, the enclosing member can be accessed using explicit qualifiers.
Within the inner class, its enclosing instance is referred to as
A class member in the enclosing scope can be explicitly referred to as
There is a difference between implicit and explicit access as far as the variables are concerned. While the implicit reference allows access to variables with any type of modifiers, the explicit reference does not allow access to private variables. An explicit reference to a private variable is detected at the compile time itself.
A member inner class can extend a class and/or implement interfaces. The base classes or interfaces can reside within or outside the enclosing scope. Just like a top-level class, an inner class will inherit members (that includes member classes) from its super class. If an inner class has its own nested inner classes, those inner classes also inherit the super class members.
If a member with the same name and signature is available in its outer scope as well as in the super class, without the explicit reference, the super class member takes precedence over the outer scope. As mentioned before, an explicit reference is required whenever such a member in the enclosing scope needs to be used.
Constructing Inner Class Objects
Inner class can be constructed within as well as outside the enclosing scope. Within that scope, an inner object is created just like any other class in the package. However, outside the enclosing scope an instance of the enclosing class is required to instantiate an object from an inner class. This will involve two steps:
1. Creating enclosing class instances
2. Creating an inner class instance
The syntax is as follows:
Extending Inner Classes
There are three different cases involved in extending an inner class:
1. Extending within the enclosing scope: Within the scope of an enclosing class, it is just like another class in the same package.
2. Extending outside the enclosing scope: Since an inner object can not exist without an instance of the enclosing class, the constructor for the inner class should have the enclosing class as one of the arguments. In addition, the first statement in the constructor should invoke the super class constructor with the following syntax:
The InnerOneExtended class in Listing 4 extends the InnerNestedOne class. As you can see from the example, the constructor has its immediate instance as one of the arguments. It invokes the super class constructor by using the super keyword. You can also see that all of the enclosing instances need to be created in order to create an instance of the InnerOneExtended class.
3. Extending in inherited classes: A non-static top-level class can inherit inner classes. In the example shown in Listing 5, the OuterMost class is subclassed. Its subclasses automatically inherit non-private members including the inner classes. The InnerNestedOne class is subclassed and the printAllClasses method is overriden.
There are two types of local classes: Named and anonymous classes.
Named Local Classes
A named class is declared within a block, has a name and can have a constructor. Since local classes are not available outside the block, they can not be associated with any access modifiers. Associating an access modifier will result in a compile-time error. However, just like member inner classes, named local classes can be abstract or final, but can't be static.
An anonymous class is an inner class that has no name or constructor. Why would you need such a class? With anonymous classes, it is possible to embed a chunk of code within an expression. A typical use would be to pass the anonymous class as an argument to a method.
No modifiers can be associated with an anonymous class. The syntax for the anonymous class starts with the keyword new. It is followed by the type, which can be either a class or an interface. Anonymous classes don't use the extends or implements keywords.
When an anonymous class is of the class type, it extends that class. The anonymous class can override the methods in the class it extends. In the example in Listing 6, the anonymous class is of WindowAdapter type, which is class in java.awt.event. It has several methods. The anonymous class in this example overrides the windowClosed method.
When an anonymous class is of the interface type, it has to implement that interface. In the dispBtn example in Listing7, the anonymous class is of ActionListener type. It implements the ActionPerformed method which is specified in the ActionListener interface. The ActionPerformed method is invoked only when dispBtn is pressed.
Anonymous classes are typically meant for a small chunk of code. Since they are not reusable, it is preferable to use a named class when the code size is large. Anonymous classes are extremely useful in event handling. Using anonymous classes, adapters can be declared exactly in the place they are used.
Whether it is a named or an anonymous class, the members of the enclosing class can be used with the same rules that are applicable to member inner classes. However, the local classes cannot access the non-final local variables in the enclosing code block because of potential synchronization problems. A local class object can exist even after the enclosing block has finished executing. In the examples in Listings 7 and 8, the anonymous class methods are invoked only when the corresponding event occurs. By that time, the createGUI methods would have finished executing.
An Application Using Inner Classes
The application shown in Figure 1 was originally developed using JDK 1.0. This was modified to use the new delegation event model and inner classes. In addition, a few more classes were added to include menus on the application frame.
There are two main GUI-related classes: CommandPanel and FrameMenubar. The CommandPanel class is the main GUI class which has three inner classes: ImageSelectPanel, CinePanel and StatsPanel. Each of these classes create a panel with AWT components. In these panels, anonymous classes are used to handle events originating from these components.
The FrameMenubar class creates a menu bar which contains three menus: File, Locale and Help. Each of the menus have several menu items. The Help menu has two menu items: Help and About. When clicked, these two menu items spawn dialog boxes. Listing 8 shows the adapter class for the About menu item. This class itself is an inner class of FrameMenubar which creates the about MenuItem component. Here, the AboutAdapter object is constructed and passed as an argument to the about MenuItem's addActionListener method.
The AboutAdapter class implements the actionPerformed method. In this method, a dialog box is constructed using the OkBox class, which is a subclass of the AWT Dialog component. Some variables in the enclosing class are passed as arguments to the OkBox constructor. This dialog box has an OK button. In order to register for the OK button action events, an anonymous class is passed as an argument to the addActionListener method. Note that this class also has the actionPerformed method. When the About menu item is clicked, the ActionPerformed method in the AboutAdapter is invoked. This would spawn a dialog box. When the OK button in the dialog box is clicked, the ActionPerformed method in the anonymous class is invoked. Upon execution of this code, the dialog box is closed. This example shows how adapters can be created within adapters using inner classes.
Although you can write Java programs without using inner classes, such programs would be bulky, less readable and often impractical (especially with the new event model). You can expect future applications/applets to make use of inner classes extensively. Java programs in such applications will look a lot different from programs written using the previous Java releases. While inner classes can be used anywhere, their use will be prominent in GUI-related programming and event handlers.
Using inner classes is not always easy. The syntax is often complicated and scope and visibility rules are not very intuitive. Once you cross these hurdles, it is hard to stop you from using this elegant feature.
1. Gosling J, Joy B and Steele G, "Javaª Language Specification", Addison-Wesley, 1996.
2. "Inner Classes in Javaª 1.1", Draft, Sun Microsystems, Nov., 1996.
The IoT is changing the way enterprises conduct business. In his session at @ThingsExpo, Eric Hoffman, Vice President at EastBanc Technologies, discuss how businesses can gain an edge over competitors by empowering consumers to take control through IoT. We'll cite examples such as a Washington, D.C.-based sports club that leveraged IoT and the cloud to develop a comprehensive booking system. He'll also highlight how IoT can revitalize and restore outdated business models, making them profitable...
May. 26, 2016 06:30 AM EDT Reads: 2,648
SYS-CON Events announced today that Commvault, a global leader in enterprise data protection and information management, has been named “Bronze Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY, and the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Commvault is a leading provider of data protection and information management...
May. 26, 2016 06:30 AM EDT Reads: 2,813
Companies can harness IoT and predictive analytics to sustain business continuity; predict and manage site performance during emergencies; minimize expensive reactive maintenance; and forecast equipment and maintenance budgets and expenditures. Providing cost-effective, uninterrupted service is challenging, particularly for organizations with geographically dispersed operations.
May. 26, 2016 06:15 AM EDT Reads: 1,673
SYS-CON Events announced today Object Management Group® has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY, and the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
May. 26, 2016 06:15 AM EDT Reads: 2,260
SYS-CON Events announced today that Alert Logic, Inc., the leading provider of Security-as-a-Service solutions for the cloud, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Alert Logic, Inc., provides Security-as-a-Service for on-premises, cloud, and hybrid infrastructures, delivering deep security insight and continuous protection for customers at a lower cost than traditional security solutions. Ful...
May. 26, 2016 05:45 AM EDT Reads: 2,617
SYS-CON Events announced today that MobiDev will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. MobiDev is a software company that develops and delivers turn-key mobile apps, websites, web services, and complex software systems for startups and enterprises. Since 2009 it has grown from a small group of passionate engineers and business managers to a full-scale mobile software company with over 200 develope...
May. 26, 2016 05:15 AM EDT Reads: 2,404
WebRTC is bringing significant change to the communications landscape that will bridge the worlds of web and telephony, making the Internet the new standard for communications. Cloud9 took the road less traveled and used WebRTC to create a downloadable enterprise-grade communications platform that is changing the communication dynamic in the financial sector. In his session at @ThingsExpo, Leo Papadopoulos, CTO of Cloud9, will discuss the importance of WebRTC and how it enables companies to fo...
May. 26, 2016 05:00 AM EDT Reads: 2,460
SYS-CON Events announced today that EastBanc Technologies will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. EastBanc Technologies has been working at the frontier of technology since 1999. Today, the firm provides full-lifecycle software development delivering flexible technology solutions that seamlessly integrate with existing systems – whether on premise or cloud. EastBanc Technologies partners with p...
May. 26, 2016 05:00 AM EDT Reads: 1,983
SoftLayer operates a global cloud infrastructure platform built for Internet scale. With a global footprint of data centers and network points of presence, SoftLayer provides infrastructure as a service to leading-edge customers ranging from Web startups to global enterprises. SoftLayer's modular architecture, full-featured API, and sophisticated automation provide unparalleled performance and control. Its flexible unified platform seamlessly spans physical and virtual devices linked via a world...
May. 26, 2016 04:30 AM EDT Reads: 1,842
SYS-CON Events announced today TechTarget has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY, and the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. TechTarget is the Web’s leading destination for serious technology buyers researching and making enterprise technology decisions. Its extensive global networ...
May. 26, 2016 04:30 AM EDT Reads: 3,080
SYS-CON Events announced today that BMC Software has been named "Siver Sponsor" of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2015 at the Javits Center in New York, New York. BMC is a global leader in innovative software solutions that help businesses transform into digital enterprises for the ultimate competitive advantage. BMC Digital Enterprise Management is a set of innovative IT solutions designed to make digital business fast, seamless, and optimized from mainframe to mo...
May. 26, 2016 04:00 AM EDT Reads: 1,912
SYS-CON Events announced today that Tintri Inc., a leading producer of VM-aware storage (VAS) for virtualization and cloud environments, will exhibit at the 18th International CloudExpo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, New York, and the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
May. 26, 2016 03:45 AM EDT Reads: 2,140
SYS-CON Events announced today BZ Media LLC has been named “Media Sponsor” of SYS-CON's 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. BZ Media LLC is a high-tech media company that produces technical conferences and expositions, and publishes a magazine, newsletters and websites in the software development, SharePoint, mobile development and Commercial Drone markets.
May. 26, 2016 03:00 AM EDT Reads: 3,446
SYS-CON Events announced today that MangoApps will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. MangoApps provides modern company intranets and team collaboration software, allowing workers to stay connected and productive from anywhere in the world and from any device. For more information, please visit https://www.mangoapps.com/.
May. 26, 2016 12:45 AM EDT Reads: 578
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, wh...
May. 26, 2016 12:00 AM EDT Reads: 1,899
SYS-CON Events announced today that ContentMX, the marketing technology and services company with a singular mission to increase engagement and drive more conversations for enterprise, channel and SMB technology marketers, has been named “Sponsor & Exhibitor Lounge Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2016, at the Javits Center in New York City, New York. “CloudExpo is a great opportunity to start a conversation with new prospects, but what happens after the...
May. 25, 2016 10:00 PM EDT Reads: 926
The essence of data analysis involves setting up data pipelines that consist of several operations that are chained together – starting from data collection, data quality checks, data integration, data analysis and data visualization (including the setting up of interaction paths in that visualization). In our opinion, the challenges stem from the technology diversity at each stage of the data pipeline as well as the lack of process around the analysis.
May. 25, 2016 08:30 PM EDT Reads: 1,259
The 19th International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Containers, Microservices and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportunity. Submit y...
May. 25, 2016 06:00 PM EDT Reads: 1,901
Internet of @ThingsExpo, taking place November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with the 19th International Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world and ThingsExpo New York Call for Papers is now open.
May. 25, 2016 05:00 PM EDT Reads: 1,734
Designing IoT applications is complex, but deploying them in a scalable fashion is even more complex. A scalable, API first IaaS cloud is a good start, but in order to understand the various components specific to deploying IoT applications, one needs to understand the architecture of these applications and figure out how to scale these components independently. In his session at @ThingsExpo, Nara Rajagopalan is CEO of Accelerite, will discuss the fundamental architecture of IoT applications, ...
May. 25, 2016 04:45 PM EDT Reads: 998