C#基础:父类 = new 子类() 的效果和作用

代码如下:

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

namespace StudentClassExample
{
    public class Son : Parent
    {
        public Son()
        {
            a = 1;
        }
    }

    public class Parent
    {
        public int a { get; set; }
        public int Geta()
        {
            return a;
        }
    }


    // 主程序
    class Program
    {
        static void Main(string[] args)
        {
            Son son = new Son();//1

            Parent parent = new Son();//父类指向子类,可以调用子类方法和使用子类变量(多态)parent.a=1
            int result = parent.Geta();//1


            Parent parent2 = new Parent();//parent.a=0
            int result2 = parent.Geta();//0
        }
    }
}
  • Son 类的构造函数初始化了 a 的值为 1,因此 parent(指向 Son 实例)的 a 为 1。
  • parent2 是 Parent 的实例,a 默认为 0。
  • 父类 = new 子类() :子类实例赋值给父类引用,可以在运行时决定具体调用哪个子类的方法或属性,体现多态。

 

你可能感兴趣的:(C#基础,servlet)