java部分知识

来源:互联网 发布:淘宝网可爱宝贝纸尿裤 编辑:程序博客网 时间:2024/06/01 07:33

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

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

 

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

 

分别写两个例子来说明:

 

接口做为参数传递 

 

[c-sharp] view plaincopy
  1. class Program  
  2.    {  
  3.        static void Main(string[] args)  
  4.        {  
  5.            Program p = new Program();  
  6.            Man m = new Man();         //这里,想实现谁接口里的方法,就实例化谁,然后在下边就传谁  
  7.            //Woman w = new Woman();  
  8.            p.Get(w);                  //传递的是实现了接口的对象            
  9.            Console.ReadLine();  
  10.        }  
  11.        public void Get(IPerson ipn)   //接口做为参数传递  
  12.        {  
  13.            ipn.Say();  
  14.        }  
  15.    }  
  16.    /// <summary>  
  17.    /// 一个人类的接口  
  18.    /// </summary>  
  19.    public interface IPerson   
  20.    {  
  21.        void Say();  
  22.    }  
  23.    /// <summary>  
  24.    /// 一个男人的类  
  25.    /// </summary>  
  26.    public class Man : IPerson  
  27.    {       
  28.        public void Say()  
  29.        {  
  30.            Console.WriteLine("我是一个男人");  
  31.        }  
  32.    }  
  33.    /// <summary>  
  34.    /// 一个女人的类  
  35.    /// </summary>  
  36.    public class Woman : IPerson  
  37.    {  
  38.        public void Say()  
  39.        {  
  40.            Console.WriteLine("我是一个女人");  
  41.        }  
  42.    }  

 

 

接口做为参数返回 

 

[c-sharp] view plaincopy
  1. class Program  
  2.   {  
  3.       static void Main(string[] args)  
  4.       {  
  5.           string a = Console.ReadLine();  
  6.           Program pr = new Program();  
  7.           pr.Getsay(a);  
  8.           Console.ReadLine();  
  9.       }  
  10.       public Person Getsay(string a)   
  11.       {  
  12.           Person p = null;  
  13.           switch (a)   
  14.           {  
  15.               case "1":  
  16.                   p = new Man();          
  17.                   p.Say();  
  18.                   break;  
  19.               case "2":  
  20.                   p = new Woman();  
  21.                   p.Say();  
  22.                   break;  
  23.           }  
  24.           return p;  
  25.       }  
  26.   }  
  27.   public interface Person   
  28.   {  
  29.       void Say();  
  30.   }  
  31.   public class Man : Person  
  32.   {  
  33.       public void Say()  
  34.       {  
  35.           Console.WriteLine("我是男人");  
  36.       }  
  37.   }  
  38.   public class Woman : Person  
  39.   {  
  40.       public void Say()  
  41.       {  
  42.           Console.WriteLine("我是女人");  
  43.       }  
  44.   }  

 

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

 

抽象类的传递和接口一样。不再说了

0 0
原创粉丝点击