4.3. Extracting and Implementing Interfaces
Problem
You want to extract an interface from a class.
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.
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);
}
}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
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);
}Tip
You also can create new interfaces from scratch by selecting File→ New→ Interface.
Implementing ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access