zoukankan      html  css  js  c++  java
  • 抽象类与接口异同

     1. 抽象类用abstrac修饰, 如abstrac class E。

       抽象类里的抽象方法也用abstract修饰,如public abstract override void DoWork(int i);

       抽象类里可由数据成员,可以实现方法。

       当抽象类从基类继承虚方法时,抽象类可以使用抽象方法重写该虚方法。如public abstract override void DoWork(int i);

            public class D
            {
                public virtual void DoWork(int i)
                {
                    // Original implementation.
                }
            }
    
            public abstract class E : D
            {
                public abstract override void DoWork(int i);
    
                public abstract void Open();
    
                public void NormalFoo()
                {
                    this.i = 10;
                    this.name = "Lucy";
                    Console.WriteLine("no virtual, no abstract function.{0}, {1}", this.i, this.name);
                }
    
                private int i;
                private string name;
            }
    
            public class F : E
            {
                public override void DoWork(int i)
                {
                    // New implementation.
                }
    
                public override void Open()
                {
                    throw new NotImplementedException();
                }
            }

    接口只能包括方法,属性、索引器、事件,

            interface IInterface
            {
                void Test();
                string this[int id] { get; }
                string Name { get; set; }
                event CompeleteEventHandler WorkCompleted;
            }
    
            class MyClass3 : IInterface
            {
                public void Test() 
                {
                    this.WorkCompleted();
                }
    
                public string this[int id] { get { return ""; } }
                public string Name { get{return "";} set{} }
    
                public event CompeleteEventHandler WorkCompleted;
            }

    相同与区别:

    都不能实例化。

    接口表达的是行为的规范和契约,代表的是一种能做某事能力。IEnumerable,IEnumerator, ICloneable,

    抽象类通常定义在关系密切的类层次之中,处于较上位置,一个类一次可以实现若干个接口,但是只能扩展一个父类 。

    而接口大多数是处于关系疏松但都实现某一功能的类中.

    抽象类定义了你是什么,接口规定了你能做什么。比如一个具体的门继承自门这个抽象类,但同时又实现了门铃的接口,门定义了你是什么,门铃规定了你还能做什么。

     

  • 相关阅读:
    洛谷 P1474 货币系统 Money Systems 题解
    洛谷 P5146 最大差值 题解
    洛谷 P1880 [NOI1995]石子合并 题解
    洛谷 P1063 能量项链 题解
    洛谷 P3385 【模板】负环 题解
    洛谷 P1522 牛的旅行 Cow Tours 题解
    洛谷 P2212 [USACO14MAR]浇地Watering the Fields 题解
    浅谈 C 语言中模块化设计的范式
    内联函数(Inline Functions)
    C++中全局变量的声明和定义
  • 原文地址:https://www.cnblogs.com/dirichlet/p/3317996.html
Copyright © 2011-2022 走看看