说我有很多代码,比如..
"
System.out.println("This is code");
System.out.println("This is code");
System.out.println("This is code");
System.out.println("This is code");
"
这个相同的代码不断出现在我的程序中,我可以将它缩短为一行,我可以在将来调用它吗?
答案 0 :(得分:2)
为什么不为它使用for循环,以及在你使用它时的方法:
public void doStuff()
{
for(int i = 0; i < 20; i++){
System.out.println("This is code");
}
}
答案 1 :(得分:0)
通过提出这个问题“怀疑的好处”我认为他的意思是在公共接口类中使用toString()方法,然后在子类中实现此方法。类似的东西:
public interface printStuff{
public String toString();
}
public class someclass implements toString{
public String toString(){
return //somestuff }
}
public class some_other_class implements toString{
public String toString(){
return //somestuff }
} // and so ON