• 子类构造函数会默认调用父类无参构造函数


    1.调用父类无参构造函数是默认的!

    子类的构造方法默认都去访问了父类的无参构造方法:在子类中的构造方法后都有一行默认语句 base()

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    class Fu
    {   public Fu()
        {
            Console.WriteLine("fu");
        }
    }
    class Zi : Fu
    {
        public Zi()
            : base()//不管是否显式调用,控制台都会输出fu
        {
            Console.WriteLine("zi");
        }
    }
    Zi z = new Zi();

    先执行父类的构造函数把父类初始化完成,再初始化子类的。

     

    2.如何访问父类的有参构造函数?

    可以通过super(参数)去访问父类中的有参构造函数。可以通过this(参数...)去访问本类中的其他构造函数。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    class Fu
        public Fu(int a)
        {
            Console.WriteLine("fu"+a);
        }
    }
    class Zi : Fu
        public Zi():base(0)//调用父类有参构造函数
        {
            Console.WriteLine("zi");
        }
        public Zi(int a):base(a)
        {
            Console.WriteLine("zi"+a);
        }
    }

    如果定义了构造函数,则类就不会有默认的无参构造函数;如果父类中没有默认的,则子类构造函数必须显示调用父类的构造函数

  • 相关阅读:
    204. Count Primes (Integer)
    203. Remove Linked List Elements (List)
    202. Happy Number (INT)
    201. Bitwise AND of Numbers Range (Bit)
    200. Number of Islands (Graph)
    199. Binary Tree Right Side View (Tree, Stack)
    198. House Robber(Array; DP)
    191. Number of 1 Bits (Int; Bit)
    190. Reverse Bits (Int; Bit)
    189. Rotate Array(Array)
  • 原文地址:https://www.cnblogs.com/mcad/p/4193266.html
Copyright © 2020-2023  润新知