zoukankan      html  css  js  c++  java
  • 接口类型的变量引用实现接口的类的实例

    一、前言

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

    二、实例

    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,实现了方法在运行时的动态绑定,充分利用了“一个接口,多个方法”  

    三、注意

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

          

  • 相关阅读:
    [转]MFC与Qt的内存管理
    [转]QT项目生成流程例图
    [转]vc中nmake.exe cl.exe 的使用
    android_layout_linearlayout(二)
    android_layout_relativelayout(一)
    android_layout_linearlayout(一)
    android_layout_relativelayout(二)
    android_activity_研究(一)
    两个线程解决一个线程卡之路
    android_layout_framelayout
  • 原文地址:https://www.cnblogs.com/YanYongSong/p/5242377.html
Copyright © 2011-2022 走看看