C#的面向对象特性之继承

using System;
using System.Collections;
using System.Collections.Generic;

namespace codeTest
{
    //在现有类(称为基类、父类)上建立新类(称为派生类、子类)的处理过程为继承。
    //派生类能自动获取基类(除了构造函数和析构函数外的所有成员),
    //可以在派生类中添加新的属性和方法扩展其功能。
    //继承的单一性指派生类只能从一个基类中继承,不能同时继承多个基类。
    //派生类只能访问基类中public,protected,internal修饰的成员 
    class Program
    {
        static void Main(string[] args)
        {
      
            Dog _dog = new Dog(10);   //先调用基类构造方法,再调用之类构造方法

            //情况1:在基类中定义了virtual方法,但在派生类中没有重写该虚方法。
            //那么在对派生类实例的调用中,该虚方法使用的是基类定义的方法。
            Animal _dog1 = new Dog();
            _dog1.Junmp();     //调用基类方法
            ((Dog)_dog1).Junmp();
            //情况2:在基类中定义了virtual方法,然后在派生类中使用override重写该方法。
            //那么在对派生类实例的调用中,该虚方法使用的是派生重写的方法。 
            Animal _dog2 = new Dog();
            _dog1.Run();     //调用子类方法
            Console.ReadLine();
        }
    }

    class Animal
    {
        public Animal()
        {
            Console.WriteLine("Animal constructor");
        }

        public Animal(int age)
        {
            Console.WriteLine(string.Format("Animal age is {0}",age));
        }

        public int Age
        {
            get;
            set;
        }

        public virtual void Run()
        {
            Console.WriteLine("Animal is Run!");
        }

        public void Junmp()
        {
            Console.WriteLine("Animal is Junmp!");
        }
    }

    /// <summary>
    /// 可以对父类virtual重写,也可以不重写,不重写时调用基类方法
    /// sealed修饰不可以继承的类
    /// </summary>
    class Dog : Animal
    {
        public Dog()
        {
            Console.WriteLine("Dog constructor");
        }

        public Dog(int age) 
            :base(age)  //调用基类构造函数
        {
            Console.WriteLine(string.Format("Dog age is {0}", age));
        }

        public Dog(string Name)
            : this()  //调用本身构造函数
        {
            Console.WriteLine(string.Format("Dog Name is {0}", Name));
        }

        public override void Run()
        {
            Console.WriteLine("Dog is Run!");
        }

        public new void Junmp()
        {
            Console.WriteLine("Dog is Junmp!");
        }
    }


    abstract class People
    {
        public abstract void GetName();
    }

    class Man: People
    {
        //abstract关键字只能用在抽象类中修饰方法,并且没有具体的实现。
        //抽象方法的实现必须在派生类中使用override关键字来实现。
        public override void GetName()
        {
            Console.WriteLine("Man name");
        }
    }
}
原文地址:https://www.cnblogs.com/lgxlsm/p/2977981.html