c#面向对象特征之继承开发实例


2.如果有多个构造函数时:
首先会调用父类的 默认的构造函数,然后在 调用 子类具体的构造函数。 此时Dog(int age)函数为下图所示。

3.若要人为调用基类中的某个具体的构造函数则在Dog(int age)函数修改为:Dog(int age):base(int)

4.两个构造函数之间进行引用时可以把Dog(int age):base(int)改为Dog(int age):this( )    最后结果为输出表最后三行.



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

/*实例化对象时,会先调用基类的构造函数,再调用子类的构造函数*/

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dog dog = new Dog();
            dog.age = 10;
            dog.Byte();
            //抽象函数没有被重写也可以被子类继承
            dog.GetAge();
            dog.BitMan();

            //查看运行结果,得出构造函数由多个组成时的运行顺序检测:
            Dog oldDog = new Dog(10);

            Console.ReadLine();
        }
    }

    class Animal {

        public Animal() {
            Console.WriteLine("Animal Constructor!");
        }

        public Animal(int age) {
            Console.WriteLine("Old Animal!");
            this.age = age;
        }

        public int age
        {
            get;
            set;
        }

        //抽象函数--需要在继承的子类中实现
        public virtual void Byte() {
            Console.WriteLine("Animal byte!");
        }
        //不重写也可以被子类继承
        public virtual void GetAge() {
            Console.WriteLine(age);
        }

        //不用重写,如果重写的话则在子类中对应的函数需要添加new关键字,否则编译不通过
        public void BitMan() {
            Console.WriteLine("Animal bite man!");
        }

    }

    //overrade重写Byte()
    sealed class Dog : Animal//sealed表示该类无法被继承
    {
        public Dog() {
            Console.WriteLine("Dog Constructor!");
        }

        public Dog(int age) : this(){
            Console.WriteLine("Old Dog!");
            this.age = age;
        }

        public override void Byte()
        {
            Console.WriteLine("Dog byte!");
        }

        public new void BitMan() {//new 关键字使得基类中的方法被隐藏。
            Console.WriteLine("Dog bit man!");
        }
    }
}

5.override 与new 的区别。

图片第三行如果不强制转换的话,就会调用父类中的getByte方法

    class Program
    {
        static void Main(string[] args)
        {
            //子类中用new重写方法,只是把父类中相应的方法隐藏了,而override是重写了基类中相应的方法
            Animal dog = new Dog();
            dog.Byte();
            //dog.BitMan();显示的是父类中的BitMan()方法
            ((Dog)dog).BitMan();//显示的是子类中的BitMan()方法
        }
    }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值