Note(5):对接口的理解(二)

来源:互联网 发布:2017淘宝客骗取佣金 编辑:程序博客网 时间:2024/06/05 03:54

以前总觉得接口没什么用处,现在开始慢慢的了解到接口在编程中是能起到很大作用的。为了更好的理解接口的应用,我又写了一些相关的测试程序代码。

       接口IPerson,类Mary和类Tom(代码如Note 4:对接口的理解(一)),

       新添加的类GetPerson,功能是简单的为用户提供人员:

       public class GetPerson {

       private int mary=1;               //mark whether Mary is rest.

       private int tom=0;                 //mark whether Tom is rest.

      

       public IPerson applyPerson(){

              if(mary==0){

                     this.mary=1;

                     return new Mary("Mary");

              }

              if(tom==0){

                     this.tom=1;

                     return new Tom("Tom");

              }

              return null;

       }

}

Main方法:

public class Main {

       public static void main(String[] args) {

              GetPerson gp=new GetPerson();

             

              IPerson p1=gp.applyPerson();

              if(p1==null){

                     System.out.println("Sorry! No person is rest!");

              }else{

                     System.out.println(p1.getName()+" is emploied for you.");

                     p1.smile();

                     p1.talk("Hello! I am "+p1.getName());

              }

             

              IPerson p2=gp.applyPerson();

              if(p2==null){

                     System.out.println("Sorry! No person is rest!");

              }else{

                     System.out.println(p2.getName()+" is emploied for you.");

                     p2.smile();

                     p2.talk("Hello! I am "+p2.getName());

              }

}

我们可以看到,当调用的方法返回的数据类型是不确定的时候,使用接口,就可以很好的来存储和操作。当然,这样操作的前提是,返回的数据类型是实现了同一个接口的,而且,后续使用接口进行的操作应该是在接口中事先声明过的。 
原创粉丝点击