面向对象——(2)多态

1、多态的含义

同一操作作用于不同的对象,可以有不同的解释,产生不同的执行结果。

2、多态的类型


(1)编译时的多态性

编译时的多态性是通过重载来实现的,对于非虚的成员来说,系统在编译时,根据传递的参数、返回的类型等信息决定实现何种操作。

(2)运行时的多态性

运行时的多态性就是指知道系统运行时,才根据实际情况决定实现何种操作。

C#中运行时的多态性是通过覆写虚成员实现。

3、重载与覆写


(1)重载:

方法名必须相同;

参数列表必须不相同;

返回值类型可以不相同。

(2)覆写

子类为满足自己的需要来重复定义某个方法的不同实现。通过override关键字来实现覆写,并且只有虚方法和抽象方法才能被覆写。

特点:

方法名称相同;

参数列表相同;

返回值类型相同。

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

namespace ConsoleApplication13
{
    class Program
    {
	//调用
        static void Main(string[] args)
        {
            Square tt = new Square();
            Console.WriteLine(tt.Getsides());

            Triangle dd = new Triangle();
            Console.WriteLine(dd.Getsides());


        }
    }

    /// <summary>
    ///定义一个Sharp图形类
    /// </summary>
    abstract public class Sharp
    {
        public abstract int Getsides();
    }
   
    /// <summary>
    ///  //派生类:Square和Triangle
    /// </summary>
    public class Square : Sharp
    {
        public override int Getsides()
        {
            return 1;
        }
    }

    public class Triangle : Sharp
    {

        public override int Getsides()
        {
            return 2;
        }
    }

}





   
posted @ 2014-01-23 19:36  Sherry&Yang  阅读(181)  评论(0编辑  收藏  举报