The subclass constructor will call the parent class without the parameter constructor by default

Source: Internet
Author: User

1. Calling the parent class without a parameter constructor is the default!

The constructor method of a subclass accesses the parameterless construction method of the parent class by default: There is a row of default statement base () after the constructor method in the child class

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

The constructor of the parent class is executed before the parent class is initialized and the subclass is initialized.

2. How do I access the parameter constructor of a parent class?

You can access the parameter constructors in the parent class through super (parameters). Can pass this (parameter ...) To access other constructors in this class.

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

If a constructor is defined, the class does not have a default parameterless constructor, and if there is no default in the parent class, the subclass constructor must display the constructor that invokes the parent class


The subclass constructor will call the parent class without the parameter constructor by default

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.