C# 继承 多态 密封

来源:互联网 发布:mac怎么下载软件 编辑:程序博客网 时间:2024/04/24 19:00

继承:


class 基类类名

{

     ... ... ;

}


class 派生类类名:基类类名

{

    ... ...;

}



覆盖new:

class A{

    public double getArea(){

        return 0;

    }

}

class B :A{

    public new double getArea(){

        return 10;

    }

}

class C : A{

    public new double getArea(){

        return 100;

    }

}


多态:

编译时多态性 -- 重载

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

namespace ConstructorAndDistructor
{
    class A
    {
        public double getArea(){
            return 0.0;
        }
        //public int getArea()
        //{
        //    return 0;
        //}这个不是重载,参数类型,个数。
        public double getArea(double r)
        {
            return Math.PI*r*r;
        }
        public double getArea(double length, double height)
        {
            return length * height;
        }
        public int getArea(int length, int height)
        {
            return length * height;
        }

    }
}

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

namespace ConstructorAndDistructor
{
    class Project
    {
        static void Main(string[] args)
        {
            A a1 = new A();//A()调用无参构造函数
            Console.WriteLine(a1.getArea());
            Console.WriteLine(a1.getArea(3));
            Console.WriteLine(a1.getArea(4,5));
        }
    }
}


运行时多态性 --  重写override

class A{

    public virtual double getArea(){

        return 0;

    }

}

class B:A{

    public override double getArea(){

        return 10;

    }

}


至于覆盖和重写的区别是什么,我也不太清楚,大多数情况应该可以通用的,除非你要做什么强制类型转换,父类到子类之间的互相转换。



密封类:

sealed 放在class 前面 ==》 不被继承:没有子类。


密封方法:selead 放在 public前面 ==》不被派生类重写或继承,子类不能通过 base.XXX来调用父类的方法。

0 0
原创粉丝点击