您的位置:首页 > 其它

子类继承父类 构造函数访问问题

2008-06-03 18:40 316 查看
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()来调用父类的函数,用于对对象的赋值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: