|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.
DevOps at Cloud Expo, taking place Nov 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 19th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long dev...
Aug. 24, 2016 11:00 AM EDT Reads: 2,064
SYS-CON Events announced today Telecom Reseller 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. Telecom Reseller reports on Unified Communications, UCaaS, BPaaS for enterprise and SMBs. They report extensively on both customer premises based solutions such as IP-PBX as well as cloud based and hosted platforms.
Aug. 24, 2016 10:48 AM EDT Reads: 230
In today's uber-connected, consumer-centric, cloud-enabled, insights-driven, multi-device, global world, the focus of solutions has shifted from the product that is sold to the person who is buying the product or service. Enterprises have rebranded their business around the consumers of their products. The buyer is the person and the focus is not on the offering. The person is connected through multiple devices, wearables, at home, on the road, and in multiple locations, sometimes simultaneously...
Aug. 24, 2016 09:45 AM EDT Reads: 2,238
Pulzze Systems was happy to participate in such a premier event and thankful to be receiving the winning investment and global network support from G-Startup Worldwide. It is an exciting time for Pulzze to showcase the effectiveness of innovative technologies and enable them to make the world smarter and better. The reputable contest is held to identify promising startups around the globe that are assured to change the world through their innovative products and disruptive technologies. There w...
Aug. 24, 2016 09:36 AM EDT Reads: 198
Internet of @ThingsExpo, taking place November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 19th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices - comp...
Aug. 24, 2016 09:00 AM EDT Reads: 3,492
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, Digital Transformation, 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 opportuni...
Aug. 24, 2016 08:00 AM EDT Reads: 3,809
For basic one-to-one voice or video calling solutions, WebRTC has proven to be a very powerful technology. Although WebRTC’s core functionality is to provide secure, real-time p2p media streaming, leveraging native platform features and server-side components brings up new communication capabilities for web and native mobile applications, allowing for advanced multi-user use cases such as video broadcasting, conferencing, and media recording.
Aug. 24, 2016 07:45 AM EDT Reads: 2,062
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, will discuss the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Aug. 24, 2016 07:15 AM EDT Reads: 1,649
SYS-CON Events announced today that 910Telecom will exhibit at the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Housed in the classic Denver Gas & Electric Building, 910 15th St., 910Telecom is a carrier-neutral telecom hotel located in the heart of Denver. Adjacent to CenturyLink, AT&T, and Denver Main, 910Telecom offers connectivity to all major carriers, Internet service providers, Internet backbones and ...
Aug. 24, 2016 07:00 AM EDT Reads: 1,733
Amazon has gradually rolled out parts of its IoT offerings in the last year, but these are just the tip of the iceberg. In addition to optimizing their back-end AWS offerings, Amazon is laying the ground work to be a major force in IoT – especially in the connected home and office. Amazon is extending its reach by building on its dominant Cloud IoT platform, its Dash Button strategy, recently announced Replenishment Services, the Echo/Alexa voice recognition control platform, the 6-7 strategic...
Aug. 24, 2016 04:30 AM EDT Reads: 2,167
19th Cloud Expo, taking place November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Meanwhile, 94% of enterpri...
Aug. 24, 2016 03:30 AM EDT Reads: 2,920
Akana has announced the availability of version 8 of its API Management solution. The Akana Platform provides an end-to-end API Management solution for designing, implementing, securing, managing, monitoring, and publishing APIs. It is available as a SaaS platform, on-premises, and as a hybrid deployment. Version 8 introduces a lot of new functionality, all aimed at offering customers the richest API Management capabilities in a way that is easier than ever for API and app developers to use.
Aug. 24, 2016 02:00 AM EDT Reads: 1,401
Personalization has long been the holy grail of marketing. Simply stated, communicate the most relevant offer to the right person and you will increase sales. To achieve this, you must understand the individual. Consequently, digital marketers developed many ways to gather and leverage customer information to deliver targeted experiences. In his session at @ThingsExpo, Lou Casal, Founder and Principal Consultant at Practicala, discussed how the Internet of Things (IoT) has accelerated our abil...
Aug. 24, 2016 01:45 AM EDT Reads: 1,869
With so much going on in this space you could be forgiven for thinking you were always working with yesterday’s technologies. So much change, so quickly. What do you do if you have to build a solution from the ground up that is expected to live in the field for at least 5-10 years? This is the challenge we faced when we looked to refresh our existing 10-year-old custom hardware stack to measure the fullness of trash cans and compactors.
Aug. 24, 2016 01:00 AM EDT Reads: 1,585
The emerging Internet of Everything creates tremendous new opportunities for customer engagement and business model innovation. However, enterprises must overcome a number of critical challenges to bring these new solutions to market. In his session at @ThingsExpo, Michael Martin, CTO/CIO at nfrastructure, outlined these key challenges and recommended approaches for overcoming them to achieve speed and agility in the design, development and implementation of Internet of Everything solutions wi...
Aug. 24, 2016 12:30 AM EDT Reads: 1,871
Cloud computing is being adopted in one form or another by 94% of enterprises today. Tens of billions of new devices are being connected to The Internet of Things. And Big Data is driving this bus. An exponential increase is expected in the amount of information being processed, managed, analyzed, and acted upon by enterprise IT. This amazing is not part of some distant future - it is happening today. One report shows a 650% increase in enterprise data by 2020. Other estimates are even higher....
Aug. 24, 2016 12:00 AM EDT Reads: 2,829
I wanted to gather all of my Internet of Things (IOT) blogs into a single blog (that I could later use with my University of San Francisco (USF) Big Data “MBA” course). However as I started to pull these blogs together, I realized that my IOT discussion lacked a vision; it lacked an end point towards which an organization could drive their IOT envisioning, proof of value, app dev, data engineering and data science efforts. And I think that the IOT end point is really quite simple…
Aug. 23, 2016 11:30 PM EDT Reads: 2,224
"My role is working with customers, helping them go through this digital transformation. I spend a lot of time talking to banks, big industries, manufacturers working through how they are integrating and transforming their IT platforms and moving them forward," explained William Morrish, General Manager Product Sales at Interoute, in this SYS-CON.tv interview at 18th Cloud Expo, held June 7-9, 2016, at the Javits Center in New York City, NY.
Aug. 23, 2016 09:00 PM EDT Reads: 2,989
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 Silicon Valley Call for Papers is now open.
Aug. 23, 2016 08:45 PM EDT Reads: 3,758
Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more business becomes digital the more stakeholders are interested in this data including how it relates to business. Some of these people have never used a monitoring tool before. They have a question on their mind like “How is my application doing” but no id...
Aug. 23, 2016 08:15 PM EDT Reads: 1,646