< Day Day Up > |
Recipe 4.3 Extracting and Implementing Interfaces4.3.1 ProblemYou want to extract an interface from a class. 4.3.2 SolutionHighlight a class name and select Refactor Extract Interface, or right-click the class name and select Refactor Extract Interface. Enter the name of the interface you want to extract, select the members to declare in the interface, and click OK. 4.3.3 DiscussionEclipse refactoring enables you to extract interfaces from classes. For example, say you have the code in Example 4-2, in which the Interfaces class includes the nonstatic printem method. Example 4-2. A class from which to extract interfacespackage org.cookbook.ch04; public class Interfaces { public static void main(String[] args) { String msg = "No problem."; new Interfaces( ).printem(msg); } public void printem(String msg) { System.out.println(msg); } } 4.3.3.1 Extracting an interfaceTo extract an interface from the Interfaces class, right-click that class's name in your code, and select Refactor Extract Interface, which opens the dialog shown in Figure 4-6. Select the printem method, type in the name NewInterface, and click OK. Figure 4-6. Extracting an interfaceThis creates a new file, NewInterface.java, with the new interface you've created: package org.cookbook.ch04; public interface NewInterface { public abstract void printem(String msg); }
4.3.3.2 Implementing an interfaceYou can implement an interface by typing the implements keyword and the name of the interface you want to implement (e.g., public class ServletExample implements NewInterface). The JDT editor shows a Quick Fix light bulb to indicate which methods are missing. Click the light bulb (alternatively, you can press Ctrl-1 or select Edit Quick Fix) to let Eclipse implement the missing methods.
|
< Day Day Up > |