您的位置:首页 > 编程语言 > Java开发

java部分知识

2014-07-10 07:45 253 查看
接口作为参数传递、返回

接口做为参数传递,传递的是实现了接口的对象;

接口作为类型返回,返回的是实现了接口的对象。

 

接口的传递与返回就是围绕着上面的两句话展开的。

 

分别写两个例子来说明:

 

接口做为参数传递 :

 

[c-sharp] view
plaincopy

class Program  

   {  

       static void Main(string[] args)  

       {  

           Program p = new Program();  

           Man m = new Man();         //这里,想实现谁接口里的方法,就实例化谁,然后在下边就传谁  

           //Woman w = new Woman();  

           p.Get(w);                  //传递的是实现了接口的对象            

           Console.ReadLine();  

       }  

       public void Get(IPerson ipn)   //接口做为参数传递  

       {  

           ipn.Say();  

       }  

   }  

   /// <summary>  

   /// 一个人类的接口  

   /// </summary>  

   public interface IPerson   

   {  

       void Say();  

   }  

   /// <summary>  

   /// 一个男人的类  

   /// </summary>  

   public class Man : IPerson  

   {       

       public void Say()  

       {  

           Console.WriteLine("我是一个男人");  

       }  

   }  

   /// <summary>  

   /// 一个女人的类  

   /// </summary>  

   public class Woman : IPerson  

   {  

       public void Say()  

       {  

           Console.WriteLine("我是一个女人");  

       }  

   }  

 

 

接口做为参数返回 :

 

[c-sharp] view
plaincopy

class Program  

  {  

      static void Main(string[] args)  

      {  

          string a = Console.ReadLine();  

          Program pr = new Program();  

          pr.Getsay(a);  

          Console.ReadLine();  

      }  

      public Person Getsay(string a)   

      {  

          Person p = null;  

          switch (a)   

          {  

              case "1":  

                  p = new Man();          

                  p.Say();  

                  break;  

              case "2":  

                  p = new Woman();  

                  p.Say();  

                  break;  

          }  

          return p;  

      }  

  }  

  public interface Person   

  {  

      void Say();  

  }  

  public class Man : Person  

  {  

      public void Say()  

      {  

          Console.WriteLine("我是男人");  

      }  

  }  

  public class Woman : Person  

  {  

      public void Say()  

      {  

          Console.WriteLine("我是女人");  

      }  

  }  

 

接口做为参数返回其实就是多态。

 

抽象类的传递和接口一样。不再说了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: