我有一个简单的界面:

public interface MyInterface{
    public void method1();
}


我想要的是,每当一个类实现MyInterface时,相应的方法将始终具有默认代码。编写implements MyInterface时,我希望能够使用Eclipse的建议来自动添加代码。例如:

public class SomeClass extends AClassImForcedToExtendDueRequirements implements MyInterface{

    ...
    /*Now I use Eclipse's code-completition suggestion*/
}


然后我想遇到这种情况:

public Class SomeClass extends AClassImForcedToExtendDueRequirements implements MyInterface{

    ...
    @Override
    public void method1(){
        System.out.println("This is a default line of code, added automatically!");
    }
}


那么,如何编辑界面?谢谢

最佳答案

界面无法完成。那就是抽象类的目的。

public abstract class MyAbstractClass
{
  public abstract void myAbstractMethod()
  {
    System.out.println("Default method body");
  }
}

//calling myAbstractMethod on this will output "Default method body"
public class MyClass extends MyAbstractClass
{
 //other stuff
}

//calling myAbstractMethod on this will output "Overriden method body"
public class MyClassWithOverride extends MyAbstractClass
{
  public void myAbstractMethod()
  {
    System.out.println("Overriden method body");
  }
}


我知道Eclipse无法为您做到这一点,并且不知道任何可用的插件或它如何工作。原因是它需要从某个地方获取该默认实现,因此需要为每个要完成的接口编写并存储一个默认实现。然后,当您使用相同的方法名称实现两个接口时,就会出现(但不太可能)的问题。

10-01 08:16
查看更多