zoukankan      html  css  js  c++  java
  • 子类继承父类 构造函数访问问题

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

    namespace staticTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                   parrot parrot1 = new parrot();       
                   Console.ReadLine();
            }
           
        }
        class Bird
        {
            static Bird() //静态构造函数前面不允许有访问修饰符
            {
                Console.WriteLine("鸟类的静态构造函数调用了");

            }
            protected Bird()
            {
                Console.WriteLine("一个小鸟被创建了");
            }
         }
        class parrot:Bird
        {
            static parrot()
            {
                Console.WriteLine("鹦鹉的静态构造函数调用了");
            }
            public parrot()
            {
                Console.WriteLine("一个鹦鹉贝创建了");
            }
        }
    }

    目前的代码执行结果就是:

    鹦鹉的静态构造函数调用了
    鸟类的静态构造函数调用了
    一个小鸟被创建了
    一个鹦鹉贝创建了

    因为parrot类 继承了Bird 类 所以当调用 parrot 类的构造函数的时候首先要先调用父类的构造函数,调用完以后才调用本类的构造函数,如果父类的构造函数是private 的话就会出错。当创建对象的时候首先要调用类的静态构造函数。

    再来看看这个代码

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

    namespace staticTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                parrot parrot2 = new parrot("傻子", 123);
                Console.ReadLine();
            }
           
        }
        class Bird
        {
            static Bird() //静态构造函数前面不允许有访问修饰符
            {
                Console.WriteLine("鸟类的静态构造函数调用了");

            }
            protected Bird()
            {
                Console.WriteLine("一个小鸟被创建了");
            }
            protected int _weight;
            public Bird(int weight)
            {
                this._weight = weight;
            }
              

        }
        class parrot:Bird
        {
            static parrot()
            {
                Console.WriteLine("鹦鹉的静态构造函数调用了");
            }
            public parrot()
            {
                Console.WriteLine("一个鹦鹉贝创建了");
            }
            private string _name;
            public parrot(string name, int weight)
                : base(weight)
            {
                Console.WriteLine("一只鹦鹉诞生啦名字是{0}体重是{1}",name,weight);
            }
        }
    }

    这段代码用了带参数的构造函数,当定义了带参数的构造函数的时候 默认的构造函数就失效了 用base()来调用父类的函数,用于对对象的赋值。

  • 相关阅读:
    Apache ActiveMQ 远程代码执行漏洞 (CVE-2016-3088)案例分析
    linux 软中断过高性能优化案例
    jvm默认的并行垃圾回收器和G1垃圾回收器性能对比
    JVM性能参数优化
    一次压测中tomcat生成session释放不及时导致的频繁fullgc性能优化案例
    sed命令实现文件内容替换总结案例
    You have new mail in /var/spool/mail/root消除提示的方法
    zookeeper常用命令
    mongodb输错命令后不能删除问题
    centos环境gcc版本升级
  • 原文地址:https://www.cnblogs.com/ivy/p/1213000.html
Copyright © 2011-2022 走看看