我有一个简单的界面:
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!");
}
}
那么,如何编辑界面呢?谢谢
最佳答案
无法通过接口(interface)来完成。这就是抽象类的用途。
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 无法为您执行此操作,并且我不知道任何可用的插件或它如何工作。原因是它需要从某个地方获取默认实现,因此需要为要使用的每个接口(interface)编写并存储在某个地方。然后,当您使用相同的方法名称实现两个接口(interface)时,就会出现一个问题(尽管不太可能)。
关于java - 使用eclipse通过接口(interface)在方法中添加默认代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20372519/