我怎么知道何时创建界面?我正处于开发学习的某个阶段,我觉得我必须更多地了解接口。我经常阅读它们,但似乎我无法掌握它们。我已经阅读过这样的例子:动物基类,IAnimal界面,如'Walk','Run','GetLegs'等等 - 但我从来没有做过某些事情,感觉就像“嘿我应该使用界面这里!”我错过了什么?为什么我要掌握这么难的概念!我只是因为我可能没有意识到对一个人的具体需求而感到恐惧 - 主要是因为他们理解它们时缺少一些方面!这让我觉得自己在成为开发者方面缺少一些东西!如果有人有过这样的经历并取得了突破,我会很感激如何理解这个概念。谢谢。
3 回答
守候你守候我
TA贡献1802条经验 获得超10个赞
假设您想要模拟在您尝试入睡时可能发生的烦恼。
接口前的模型
class Mosquito {
void flyAroundYourHead(){}}class Neighbour{
void startScreaming(){}}class LampJustOutsideYourWindow(){
void shineJustThroughYourWindow() {}}正如你清楚地看到,当你试图睡觉时,很多“事情”会令人讨厌。
没有接口的类的用法
但是当谈到使用这些类时,我们遇到了问题。他们没有任何共同之处。您必须单独调用每个方法。
class TestAnnoyingThings{
void testAnnoyingThinks(Mosquito mosquito, Neighbour neighbour, LampJustOutsideYourWindow lamp){
if(mosquito != null){
mosquito.flyAroundYourHead();
}
if(neighbour!= null){
neighbour.startScreaming();
}
if(lamp!= null){
lamp.shineJustThroughYourWindow();
}
}}带接口的模型
为了克服这个问题,我们可以引入一个接口
interface Annoying{
public void annoy();}并在类中实现它
class Mosquito implements Annoying {
void flyAroundYourHead(){}
void annoy(){
flyAroundYourHead();
}}class Neighbour implements Annoying{
void startScreaming(){}
void annoy(){
startScreaming();
}}class LampJustOutsideYourWindow implements Annoying{
void shineJustThroughYourWindow() {}
void annoy(){
shineJustThroughYourWindow();
}}用于接口
这将使这些类的使用更容易
class TestAnnoyingThings{
void testAnnoyingThinks(Annoying annoying){
annoying.annoy();
}}- 3 回答
- 0 关注
- 558 浏览
添加回答
举报
0/150
提交
取消
