DekGenius.com
Previous Section  < Day Day Up >  Next Section

Recipe 4.3 Extracting and Implementing Interfaces

4.3.1 Problem

You want to extract an interface from a class.

4.3.2 Solution

Highlight 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 Discussion

Eclipse 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 interfaces
package 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 interface

To 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 interface
figs/ecb_0406.gif


This 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);
}

You also can create new interfaces from scratch by selecting File New Interface.


4.3.3.2 Implementing an interface

You 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.

You don't have to implement all of the interface's methods. Eclipse will give you the option of making your class abstract.


    Previous Section  < Day Day Up >  Next Section