C# 继承 多态 密封

继承:


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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值