|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.
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at @ThingsExpo, James Kirkland, Red Hat's Chief Architect for the Internet of Things and Intelligent Systems, described how to revolutionize your archit...
Jul. 28, 2015 06:30 PM EDT Reads: 1,370
It is one thing to build single industrial IoT applications, but what will it take to build the Smart Cities and truly society-changing applications of the future? The technology won’t be the problem, it will be the number of parties that need to work together and be aligned in their motivation to succeed. In his session at @ThingsExpo, Jason Mondanaro, Director, Product Management at Metanga, discussed how you can plan to cooperate, partner, and form lasting all-star teams to change the world and it starts with business models and monetization strategies.
Jul. 28, 2015 04:30 PM EDT Reads: 1,750
The Internet of Everything (IoE) brings together people, process, data and things to make networked connections more relevant and valuable than ever before – transforming information into knowledge and knowledge into wisdom. IoE creates new capabilities, richer experiences, and unprecedented opportunities to improve business and government operations, decision making and mission support capabilities.
Jul. 28, 2015 04:00 PM EDT Reads: 215
The Internet of Things is not only adding billions of sensors and billions of terabytes to the Internet. It is also forcing a fundamental change in the way we envision Information Technology. For the first time, more data is being created by devices at the edge of the Internet rather than from centralized systems. What does this mean for today's IT professional? In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists addressed this very serious issue of profound change in the industry.
Jul. 28, 2015 03:00 PM EDT Reads: 1,246
Discussions about cloud computing are evolving into discussions about enterprise IT in general. As enterprises increasingly migrate toward their own unique clouds, new issues such as the use of containers and microservices emerge to keep things interesting. In this Power Panel at 16th Cloud Expo, moderated by Conference Chair Roger Strukhoff, panelists addressed the state of cloud computing today, and what enterprise IT professionals need to know about how the latest topics and trends affect their organization.
Jul. 28, 2015 02:00 PM EDT Reads: 1,156
SYS-CON Events announced today that HPM Networks will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. For 20 years, HPM Networks has been integrating technology solutions that solve complex business challenges. HPM Networks has designed solutions for both SMB and enterprise customers throughout the San Francisco Bay Area.
Jul. 28, 2015 11:45 AM EDT Reads: 407
For IoT to grow as quickly as analyst firms’ project, a lot is going to fall on developers to quickly bring applications to market. But the lack of a standard development platform threatens to slow growth and make application development more time consuming and costly, much like we’ve seen in the mobile space. In his session at @ThingsExpo, Mike Weiner, Product Manager of the Omega DevCloud with KORE Telematics Inc., discussed the evolving requirements for developers as IoT matures and conducted a live demonstration of how quickly application development can happen when the need to comply wit...
Jul. 28, 2015 11:15 AM EDT Reads: 220
Converging digital disruptions is creating a major sea change - Cisco calls this the Internet of Everything (IoE). IoE is the network connection of People, Process, Data and Things, fueled by Cloud, Mobile, Social, Analytics and Security, and it represents a $19Trillion value-at-stake over the next 10 years. In her keynote at @ThingsExpo, Manjula Talreja, VP of Cisco Consulting Services, discussed IoE and the enormous opportunities it provides to public and private firms alike. She will share what businesses must do to thrive in the IoE economy, citing examples from several industry sectors.
Jul. 28, 2015 11:00 AM EDT Reads: 2,026
Growth hacking is common for startups to make unheard-of progress in building their business. Career Hacks can help Geek Girls and those who support them (yes, that's you too, Dad!) to excel in this typically male-dominated world. Get ready to learn the facts: Is there a bias against women in the tech / developer communities? Why are women 50% of the workforce, but hold only 24% of the STEM or IT positions? Some beginnings of what to do about it! In her Opening Keynote at 16th Cloud Expo, Sandy Carter, IBM General Manager Cloud Ecosystem and Developers, and a Social Business Evangelist, d...
Jul. 27, 2015 09:00 PM EDT Reads: 2,037
There will be 150 billion connected devices by 2020. New digital businesses have already disrupted value chains across every industry. APIs are at the center of the digital business. You need to understand what assets you have that can be exposed digitally, what their digital value chain is, and how to create an effective business model around that value chain to compete in this economy. No enterprise can be complacent and not engage in the digital economy. Learn how to be the disruptor and not the disruptee.
Jul. 27, 2015 10:00 AM EDT Reads: 2,017
Akana has released Envision, an enhanced API analytics platform that helps enterprises mine critical insights across their digital eco-systems, understand their customers and partners and offer value-added personalized services. “In today’s digital economy, data-driven insights are proving to be a key differentiator for businesses. Understanding the data that is being tunneled through their APIs and how it can be used to optimize their business and operations is of paramount importance,” said Alistair Farquharson, CTO of Akana.
Jul. 27, 2015 09:00 AM EDT Reads: 270
Business as usual for IT is evolving into a "Make or Buy" decision on a service-by-service conversation with input from the LOBs. How does your organization move forward with cloud? In his general session at 16th Cloud Expo, Paul Maravei, Regional Sales Manager, Hybrid Cloud and Managed Services at Cisco, discusses how Cisco and its partners offer a market-leading portfolio and ecosystem of cloud infrastructure and application services that allow you to uniquely and securely combine cloud business applications and services across multiple cloud delivery models.
Jul. 27, 2015 08:00 AM EDT Reads: 1,890
The enterprise market will drive IoT device adoption over the next five years. In his session at @ThingsExpo, John Greenough, an analyst at BI Intelligence, division of Business Insider, analyzed how companies will adopt IoT products and the associated cost of adopting those products. John Greenough is the lead analyst covering the Internet of Things for BI Intelligence- Business Insider’s paid research service. Numerous IoT companies have cited his analysis of the IoT. Prior to joining BI Intelligence, he worked analyzing bank technology for Corporate Insight and The Clearing House Payment...
Jul. 26, 2015 09:00 PM EDT Reads: 1,555
In his keynote at 16th Cloud Expo, Rodney Rogers, CEO of Virtustream, discussed the evolution of the company from inception to its recent acquisition by EMC – including personal insights, lessons learned (and some WTF moments) along the way. Learn how Virtustream’s unique approach of combining the economics and elasticity of the consumer cloud model with proper performance, application automation and security into a platform became a breakout success with enterprise customers and a natural fit for the EMC Federation.
Jul. 26, 2015 08:00 AM EDT Reads: 2,136
"Optimal Design is a technology integration and product development firm that specializes in connecting devices to the cloud," stated Joe Wascow, Co-Founder & CMO of Optimal Design, in this SYS-CON.tv interview at @ThingsExpo, held June 9-11, 2015, at the Javits Center in New York City.
Jul. 25, 2015 02:00 PM EDT Reads: 377
SYS-CON Events announced today that CommVault has been named “Bronze Sponsor” of SYS-CON's 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. A singular vision – a belief in a better way to address current and future data management needs – guides CommVault in the development of Singular Information Management® solutions for high-performance data protection, universal availability and simplified management of data on complex storage networks. CommVault's exclusive single-platform architecture gives companies unp...
Jul. 25, 2015 01:00 PM EDT Reads: 1,936
Electric Cloud and Arynga have announced a product integration partnership that will bring Continuous Delivery solutions to the automotive Internet-of-Things (IoT) market. The joint solution will help automotive manufacturers, OEMs and system integrators adopt DevOps automation and Continuous Delivery practices that reduce software build and release cycle times within the complex and specific parameters of embedded and IoT software systems.
Jul. 25, 2015 12:15 PM EDT Reads: 442
"ciqada is a combined platform of hardware modules and server products that lets people take their existing devices or new devices and lets them be accessible over the Internet for their users," noted Geoff Engelstein of ciqada, a division of Mars International, in this SYS-CON.tv interview at @ThingsExpo, held June 9-11, 2015, at the Javits Center in New York City.
Jul. 25, 2015 12:00 PM EDT Reads: 1,517
Internet of Things is moving from being a hype to a reality. Experts estimate that internet connected cars will grow to 152 million, while over 100 million internet connected wireless light bulbs and lamps will be operational by 2020. These and many other intriguing statistics highlight the importance of Internet powered devices and how market penetration is going to multiply many times over in the next few years.
Jul. 25, 2015 09:00 AM EDT Reads: 1,480
SYS-CON Events announced today that Dyn, the worldwide leader in Internet Performance, will exhibit at SYS-CON's 17th International Cloud Expo®, which will take place on November 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Dyn is a cloud-based Internet Performance company. Dyn helps companies monitor, control, and optimize online infrastructure for an exceptional end-user experience. Through a world-class network and unrivaled, objective intelligence into Internet conditions, Dyn ensures traffic gets delivered faster, safer, and more reliably than ever.
Jul. 24, 2015 11:00 PM EDT Reads: 2,043