C#

微软认为,接口就是一个规范,只说不做,那么就意味着,他的成员必须由子类来实现,也就意味着,在接口中的成员必须是公共的和抽象的。

接口就是一个抽象类,通过查看源码知道的;

实现接口的成员,并不是来重写,实现之后的接口的成员就是类的成员;

接口的方法只能通过接口对象来调用。

什么时候接口对象---所谓的接口对象就是,实现了接口的类的对象

如果一个类继承自另外一个类,同时实现多个接口,那么类的继承需要先确定,也说明:如果第一个是类,那么后面的是接口;如果第一个是接口,那么后面的都是接口。

接口作为参数,传入实现了接口的类的对象;

使用多态的三种场合:

1,声明父类变量,实例化子类对象,声明接口类型的变量,实例化实现了接口的类的对象;

2.父类做为方法的返回值类型,返回子类对象,接口作为方法的返回值类型,返回实现的接口的类的对象;

3.父类作为参数,传入子类对象,接口作为参数,传入实现了接口的类的对象。

代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 接口
 8 {
 9     /// <summary>
10     /// 接口:定义一个统一的标准
11     /// 声明接口,接口中,只包含成员的生命,不包含任何的代码实现。
12     /// 接口成员总是公有的,不添加也不需要添加public,也不能声明虚方法和虚静态方法
13     /// </summary>
14     interface IBankAccount
15     {
16         //方法
17         void PayIn(decimal amount);
18 
19         //方法
20         bool WithShowMyself(decimal amount);
21 
22         //属性
23         decimal Balance { get; }
24     }
25 
26     //实现接口的类的相应成员必须添加public修饰
27     public class SaveAccount : IBankAccount
28     {
29         //私有变量
30         private decimal banlance;
31 
32         //存款
33         public void PayIn(decimal amount)
34         {
35             banlance += amount;
36         }
37 
38         //取款
39         public bool WithShowMyself(decimal amount)
40         {
41             if (banlance >= amount)
42             {
43                 banlance -= amount;
44                 return true;
45             }
46             else
47             {
48                 Console.WriteLine("余额不足!");
49                 return false;
50             }
51         }
52 
53         //账户余额
54         public decimal Balance
55         {
56             get
57             {
58                 return banlance;
59             }
60         }
61     }
62 
63 
64     class Program
65     {
66         static void Main(string[] args)
67         {
68             //引用指向SaveAccount
69             IBankAccount ib = new SaveAccount();
70 
71             ib.PayIn(1000);
72 
73             ib.WithShowMyself(200);
74 
75             Console.WriteLine(ib.Balance);
76 
77             Console.ReadKey();
78         }
79     }
80 }
原文地址:https://www.cnblogs.com/KTblog/p/4525781.html