C# 语法练习(10): 类[二] - 继承、覆盖、多态、隐藏


继承:
using System;

class Parent
{
    public void Msg() { Console.WriteLine("Parent"); }
}

class Child : Parent { }

class Program
{
    static void Main()
    {
        Parent ObjParent = new Parent();
        Child ObjChild = new Child();

        ObjParent.Msg(); //Parent
        ObjChild.Msg();  //Parent

        Console.ReadKey();
    }
}

 
 
 
 
 

 

 

  

覆盖:
using System;

class Parent
{
    public virtual void Msg() { Console.WriteLine("Parent"); }
}

class Child : Parent 
{
    public override void Msg() { Console.WriteLine("Child"); }
}

class Program
{
    static void Main()
    {
        Parent ObjParent = new Parent();
        Child ObjChild = new Child();

        ObjParent.Msg(); //Parent
        ObjChild.Msg();  //Child

        Console.ReadKey();
    }
}

 
 
 
 
 

 

 

  

多态:
using System;

class Parent
{
    public virtual void Msg() { Console.WriteLine("Parent"); }
}

class Child1 : Parent 
{
    public override void Msg() { Console.WriteLine("Child_1"); }
}

class Child2 : Parent
{
    public override void Msg() { Console.WriteLine("Child_2"); }
}

class Program
{
    static void Main()
    {
        Parent Obj1 = new Child1();
        Parent Obj2 = new Child2();

        Obj1.Msg(); //Child_1
        Obj2.Msg(); //Child_2

        Console.ReadKey();
    }
}

 
 
 
 
 

 

 

  

隐藏:
using System;

class Parent
{
    public void Msg() { Console.WriteLine("Parent"); }
}

/* 有意隐藏应使用 new 关键字 */
class Child1 : Parent 
{
    new public void Msg() { Console.WriteLine("Child_1"); }
}

/* 无意隐藏会有提示, 但可用 */
class Child2 : Parent
{
    public void Msg() { Console.WriteLine("Child_2"); }
}

class Program
{
    static void Main()
    {
        Parent Obj1 = new Child1();
        Parent Obj2 = new Child2();
        Child1 Obj3 = new Child1();
        Child2 Obj4 = new Child2();

        Obj1.Msg(); //Parent
        Obj2.Msg(); //Parent
        Obj3.Msg(); //Child_1
        Obj4.Msg(); //Child_2

        Console.ReadKey();
    }
}

 
 
 
 
 

 

 

  

转载于:https://my.oschina.net/hermer/blog/320377

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值