|
We have seen the use of anonymous class in assignment statement. However, it can also be used while passing an argument to a method. This is especially useful when a method expects an object as an argument. For example, let us assume that a class CampingGear has a method addBike as:
package com.example.scjp.studykit;
public class CampingGear {
void addBike(Bicycle bike) { }
}
The addBike() method can be called by passing a Bicycle object. You can either create an object, store it in some variable and then call this method. Alternatively you can create an anonymous class object and pass it as argument at the time of invocation of this method as:
addBike(new Bicycle(“Tandem”) {};);
An anonymous class is a convenient way to define a (silly) little use-and-discard type of class where you don’t have to think for a trivial class names. However, they must be used with care. As it is not possible to instantiate objects of anonymous class anywhere other than where it is declared, it must be a small class doing some straightforward things. In other words, the code of anonymous class should be simple and it should be self-documenting. These are not hard and fast rules, but obviously if a class implements complex behavior then it is worth to give it a name and make it possible to instantiate and reuse it. Such complex class is probably not the best candidate of being anonymous. The event listeners in Java GUI are one of the better candidates for being anonymous inner classes.
|
|
Nested or inner classes should be used with caution. They can become very confusing for people not used to object oriented development. A general rule of thumb for nested/inner class is to use them only for an object that require less then 10-15 lines of code. |