Inner classes in methods and scopes

What youve seen so far encompasses the typical use for inner classes. In general, the code that youll write and read involving inner classes will be plain inner classes that are simple and easy to understand. However, the design for inner classes is quite complete, and there are a number of other, more obscure, ways that you can use them if you choose; inner classes can be created within a method or even an arbitrary scope. There are two reasons for doing this:

As shown previously, youre implementing an interface of some kind so
that you can create and return a reference.

Youre solving a complicated problem and you want to create a class to
aid in your solution, but you dont want it publicly available.
A class
defined within a method

A class defined within a scope inside a method

An anonymous class implementing an interface

An anonymous class extending a class that has a nondefault constructor

The class PDestination is part of dest( ) rather than being part of Parcel4. (Also notice that you could use the class identifier PDestination for an inner class inside each class in the same subdirectory without a name clash.) Therefore, PDestination cannot be accessed outside of dest( ).Notice the upcasting that occurs in the return statementnothing comes out of dest( ) except a reference to Destination, the base class. Of course, the fact that the name of the class PDestination is placed inside dest( ) doesnt mean that PDestination is not a valid object once dest( ) returns.

The next example shows how you can nest an inner class within any arbitrary scope:

The class TrackingSlip is nested inside the scope of an if statement. This does not mean that the class is conditionally createdit gets compiled along with everything else. However, its not available outside the scope in which it is defined.Other than that, it looks just like an ordinary class.