good explanations on inner classes, especially anonymous class

We’ve already seen examples of the syntax for defining and instantiating an anonymous class. We can express that syntax more formally as:

new class-name ( [ argument-list ] ) { class-body }

new interface-name () { class-body }


and Syntax for anonymous classes
Before getting into actual code in the sample program, I want to explain the syntax used to define and instantiate an anonymous class.
The definition and instantiation of an anonymous class uses one or the other of the two expressions shown in Figure 1.
new className(optional argument list){classBody}

new interfaceName(){classBody}
Figure 1

Usually, this expression is included inside a larger overall expression, such as an argument to a method call.

What does the first expression mean?

Here is how I usually explain this syntax to my students. The first expression in Figure 1 starts out fairly normal, but becomes cryptic very quickly. This expression instantiates a new object from an unnamed and previously undefined class, which automatically extends the class named className, and which cannot explicitly implement any interfaces. The body of the new class is given by classBody.

The result of executing this expression is that a new class that extends className is defined, a new object of the new class is instantiated, and the expression is replaced by a reference to the new object.



Author: lwpro2

Java J2EE professional

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s