继承之调用基类构造函数知识点和思考练习(用了三层继承,重载了各层的构造函数,以期全面实验调用基类构造函数)
知识点
(二)调用基类构造函数
构造函数可以用于初始化新对象的数据成员。派生类的构造函数不仅要初始化本类中定义的数据成员,还要初始化从基类继承来的数据成员,因此,在创建派生类的实例时,应同时调用基类的构造函数,编译器会根据类的继承层次逐渐向上浏览整个上级类,找到最顶层的基类,先调用基类的构造函数,然后再依次调用各级派生类的构造函数。
思考练习
using System; namespace NetNameSpace { public class Net { private string netAddress; public Net() { netAddress = "www"; Console.WriteLine("正在调用Net类不带参数的构造函数!netAddress被初始化为{0}", netAddress); } public Net(string netAddVar) { netAddress = netAddVar; Console.WriteLine("正在调用Net类带一个参数的构造函数!netAddress被初始化为{0}", netAddress); } } public class Blog : Net { private string blogName; public Blog() : base() { blogName = "Blog"; Console.WriteLine("正在调用Blog类不带参数的构造函数!blogName被初始化为{0}", blogName); } public Blog(string blogNameVar) : base() { blogName = blogNameVar; Console.WriteLine("正在调用Blog类带一个参数的构造函数!blogName被初始化为{0}", blogName); } public Blog(string netAddVar, string blogNameVar) : base(netAddVar) { blogName = blogNameVar; Console.WriteLine("正在调用Blog类带两个参数的构造函数!blogName被初始化为{0}", blogName); } } public class ItBlog : Blog { private string category; public ItBlog() : base() { category = "IT category"; Console.WriteLine("正在调用ItBlog类不带参数的构造函数!category被初始化为{0}", category); } public ItBlog(string cateVar) : base() { category = cateVar; Console.WriteLine("正在调用ItBlog类带一个参数的构造函数!category被初始化为{0}", category); } public ItBlog(string blogNameVar, string cateVar) : base(blogNameVar) { category = cateVar; Console.WriteLine("正在调用ItBlog类带两个参数的构造函数!category被初始化为{0}", category); } public ItBlog(string netAddVar, string blogNameVar, string cateVar) : base(netAddVar, blogNameVar) { category = cateVar; Console.WriteLine("正在调用ItBlog类带三个参数的构造函数!category被初始化为{0}", category); } } public class Program { static void Main() { Blog blog1 = new Blog(); Blog blog2 = new Blog("CNBlogs"); Blog blog3 = new Blog("www.cnblogs.com", "CNBlogs"); Console.ReadLine(); ItBlog itBlog1 = new ItBlog(); ItBlog itBlog2 = new ItBlog("DOT NET"); ItBlog itBlog3 = new ItBlog("CNBlogs", "DOT NET"); ItBlog itBlog4 = new ItBlog("www.cnblogs.com", "CNBlogs", "DOT NET"); Console.ReadLine(); } } }
输出结果
可见继承调用构造函数都是先调用最顶层的基类构造函数,再逐层往派生类调用