Java Reference
In-Depth Information
Converting an anonymous class into an inner class
The Refactor | Convert Anonymous to Inner command lets you take an anony-
mous class and change it to an inner class that can then be reused throughout its
containing class. This situation occurs most frequently during Swing develop-
ment, due to the large number of listeners, renderers, and other interfaces you
implement for the benefit of a single button or other component. This refactor-
ing is simple: Put your cursor on the anonymous class, and execute the refactor-
ing. You're asked to specify a name for the new class and order any constructor
parameters that are required. You also have the option of making the class static.
Replacing inheritance with delegation
As we discussed in chapter 3, IDEA can generate delegation methods for you,
making it easy to proxy behavior between classes. The Replace Inheritance with
Delegation refactoring concerns using delegation to provide behavior instead of
inheritance. Rather than extend a class to gain access to its behavior, you can
delegate some or all of the methods of a superclass to an instance of that super-
class encapsulated into the current class. This enables you to extend some other
class if you wish while retaining the behavior you rely on the original superclass to
provide. During the refactoring, a new constructor for your class is created,
accepting an instance of the superclass you wish to delegate to. You can also dele-
gate to an instance of an interface that you no longer wish to implement directly.
In this case, IDEA creates an inner class implementation of the interface for you,
delegating the calls to its methods to the inner class.
Execute the Refactor | Replace Inheritance with Delegation command to
access the refactoring dialog shown in figure 9.25. Select the superclass or inter-
face to which you'd like to delegate. All the accessible methods of that class are
listed in the Delegate members list. Next, specify the name of the field that will
hold the delegate instance. The option Generate getter for delegated compo-
nent should be selected if you want to access the superclass instance from outside
the current class. If you're delegating to an interface, specify the name of the
inner class that is implementing that interface. Select the methods to which you
wish to delegate, and click OK to begin refactoring.
Generalizing class references
The command Refactor | Use Interface Where Possible finds places in the
source code where it's possible to refer to the current class by its interface or one
of its superclass types. This has the effect of creating a more general reference to
the class. To use this refactoring, select the class you want to refactor, and execute
 
 
 
 
 
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search