我有一些关于界面使用的一般问题:
>为每个对象类创建接口有什么好处?
>接口应该只包含’getter’方法吗?
>为什么不也是二传手呢?
>为什么我要为每个对象类创建一个接口?它会在JUnit测试中为我服务吗?
例如 :
public interface Animal {
public getVoice();
public String getName();
}
public class Dog implements Animal {
private String name;
public getVoice(){
System.out.println("Brrr");
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
}
谢谢
最佳答案
What is the advantages in creating interface for each object class ?
没有任何优势.这不是Interfaces的用途.
Should interface only contains ‘getter’ methods? Why not also the setter?
Why should I create for each object class an interface?
同样,这不是界面的目的.将其视为冗余.
如果您了解interfaces是什么,您将意识到它们的正确用法
Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world,and this contract is enforced at build time by the compiler.