文档首页> CodeArts IDE> 用户指南> Java> 重构> 尽可能使用Interface
更新时间:2024-04-12 GMT+08:00
分享

尽可能使用Interface

此重构允许您将从基类/接口派生的指定方法的执行委托给实现同一接口的父类或内部类的实例。

执行重构

  1. 在代码编辑器中,将光标放在应通过父类/接口委托其方法的类的声明上。
  2. 在主菜单或编辑器上下文菜单中,选择Refactor>Use Interface Where Possible
  3. 在打开的Use Interface Where Possible对话框中,选择应替换当前类用法的父类/接口。想要同时替换当前类在instanceof语句中的用法,请选中在instanceof语句中Use interface/superclass in instanceof复选框。

    CodeArts IDE将自动重命名变量,以匹配重构引入的更改。如有必要,请在Rename Variables对话框中提供替代名称。

  4. 单击Refactor以应用重构。

示例

例如,让我们将print方法的使用从类InnerClass委托给它实现的接口InnerInterface

重构前

class UseInterface {

    public static void main(String[] args) {
        InnerClass innerClass = new InnerClass();
        print(innerClass);
    }

    private static void print(InnerClass innerClass) {
        innerClass.print();
    }

    private static class InnerClass implements InnerInterface {
        @Override
        public void print() {
            System.out.println("Hello World!");
        }
    }

    private static interface InnerInterface{
        void print();
    }
}

重构后

class UseInterface {

    public static void main(String[] args) {
        InnerInterface innerInterface = new InnerClass();
        print(innerInterface);
    }

    private static void print(InnerInterface innerInterface) {
        innerInterface.print();
    }

    private static class InnerClass implements InnerInterface {
        @Override
        public void print() {
            System.out.println("Hello World!");
        }
    }

    private static interface InnerInterface{
        void print();
    }
}
分享:

    相关文档

    相关产品