子类的构造函数

75 阅读1分钟

父类

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

namespace _10_子类的构造函数
{
    internal class BaseClass
    {
        private int hp;
        private int speed;

        public BaseClass()
        {
            Console.WriteLine("BaseClass构造函数");
        }

        public BaseClass(int hp, int speed)
        {
            this.hp = hp;
            this.speed = speed;
        }
    }
}

子类

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

namespace _10_子类的构造函数
{
    internal class DrivedClass:BaseClass
    {
        private int attack;
        public DrivedClass()
        {
            Console.WriteLine("构造函数:DrivedClass");
        }

        public DrivedClass(int attack)
        {
            this.attack = attack;
        }

        public DrivedClass(int attack, int hp, int speed) : base(hp, speed)
        {
            this.attack = attack;
        }
    }
}

测试

static void Main(string[] args)
{
    DrivedClass drivedClass = new DrivedClass(10,1,1);
}

总结

在子类中,通过base关键字可以调用父类的构造函数,在创建对象时候,可以通过参数选择不同的构造函数