• 接口类型的变量引用实现接口的类的实例


    一、前言

      接口的灵活性就在于“规定了一个类必须做什么,而不管你如何做”。我们可以定义一个接口类型的变量来引用实现接口的类的对象,当这个引用来调用方法时,它会根据实际引用的类的实例来判断具体调用哪个方法。

    二、实例

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using CSharpLib;

    namespace foundation
    {
    interface Inter
    {
    void fun();
    }

    public class A : Inter
    {
    public void fun()
    {
    Console.WriteLine("This is A");

    }
    }

    public class B : Inter
    {
    public void fun()
    {
    Console.WriteLine("This is B");
    Console.Read();
    }

    public void test()
    {
    Console.WriteLine("This is test");
    }
    }

    class Program
    {

    static void Main(string[] args)
    {
    Inter a;
    a = new A();
    a.fun();
    a = new B();
    a.fun();

    }
    }

    }

    输出结果为:

        This is A
        This is B

    上例中类A和类B是实现接口Inter的两个类,分别实现了接口的方法fun(),通过将类A和类B的实例赋给接口引用a,实现了方法在运行时的动态绑定,充分利用了“一个接口,多个方法”  

    三、注意

      当接口变量在调用其实现类的对象的方法时,该方法必须已经在接口中被声明,而且在接口的实现类中该实现方法的类型和参数必须与接口中所定义的精确匹配。

          

  • 相关阅读:
    排序算法<四>希尔排序
    排序算法<三>快速排序
    排序算法<二>冒泡排序
    排序算法<一>选择排序
    相信我这是水题ny1313
    斐波那契查找
    插值查找
    第四届蓝桥杯c/c++B组4
    如何使用NPM来管理你的Node.js依赖
    javascript深入学习
  • 原文地址:https://www.cnblogs.com/YanYongSong/p/5242377.html
Copyright © 2020-2023  润新知