您的位置:首页 > 其它

抽象类与抽象方法

2012-09-10 14:01 183 查看
这几天由于工作的需要,对c#抽象类中抽象类作了一些总结,虽然理解的不是很深,但是仍希望对大家有所帮助

现在首先讲解下抽象类的功能与特点:抽象类主要用于一些大范围内且无须描述很详细的东西,但它可以派生出很多子类 ,例如定义一个抽象类People, 而People类中有中国人,美国人,非洲人,故可以派生出Chinese类,American类,Africa类等。

抽象类的主要特点:在抽象类中可以定义属性,方法,事件等,这些都和类相似,但是它特有的是可以在抽象类中定义抽象方法,也就是说抽象方法只能定义在抽象类中,并且要在子类中重写,抽象类的另一大特点不能实例化,下面还是以People类来说明:

//define abstract class People

abstract class People{

string country;

public People(string country) //constructor include one argument

{

this.country=country;

}

abstract public void Country(){} //define a abstract method

}

//derive the Chinese class

class Chinese:People{

string skin;

public People(string skin,string country):base(country)

{

this.skin=skin;

}

public override void Country() //override Country method in child class

{

Console.WriteLine("i come from:{0} my skin is:{1}",country,skin);

}

}

//derive American class

class American:People{

string skin;

public American(string skin,string country):base(country)

{

this.skin=skin;

}

public override void Country()

{

Console.WriteLine("i come from:{0} my skin is{1}",country,skin);

}

}

class Africa:People{

string skin;

public Africa(string skin,string country):base(country)

{

this.skin=skin;

}

public override void Country()

{

Console.WriteLine("i come form{0} my skin is {1}",country,skin);

}

}

//instance them in Problem class

class Problem{

People[] people={new Chinese("China","yellow"),new American("America","white"),new Africa("Africa","black")};// define a people type array

foreach(People p in people)

{

Console.WriteLine(p.Country());

}

}

现在对上面的举例解析下

上面例子中总共定义了五个类,分别是抽象类People, 派生类Chinese,American,Africa 和一个Problem ,下面详细分析下这几个类:首先在抽象类中定义了一个变量country,一个构造方法和一个抽象方法,在构造方法中对country变量作了初始化,而抽象方法中则等待在子类中重写,当对抽象类People了解后,让我们再来看下派生类Chinese,在这个子类中,定义了skin(肤色)这个变量,一个构造方法,该构造方法中含有两个参数skin和country,这个构造方法继承基类的构造方法,并对skin这个变量作了初始化,至于Conutry方法则是重写了基类中Country方法,输出country和skin,另外两个派生类都是与此一样,这里我就不重复讲解了,最后在Problem类中定义了一个People类数组,在这个数组中对三个派生类作了初始化,仍后打印出p.Country()
,即可以得到每个国家的country和skin
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: