C#学习笔记07:多态
来源:互联网 发布:关系型数据库四大特征 编辑:程序博客网 时间:2024/06/05 06:11
1、多态性概念
使用同一个名称,其依据Context不同,产生不同功能。如对象调用同一函数,随着引用实例不同,实现功能也不相同。
Shape shape=newCirlce();
shape.area();
shape=new Rect();
shape.area();
在OOP编程中,实现多态一般通过子类重写父类中虚函数或抽象函数来实现,
abstract class Shape{
public abstractdouble area();
public void disp(){
…
}
}
抽象类不能实例化.(基类)
class Circle :Shape{
public overridedouble area(){
..
}
}
2、接口Interface定义与使用
接口是一种特殊类,接口中只有抽象函数与抽象属性声明。
1)接口定义
interface IShape
{
double area();
double length();
}
class Circle: IShape
{
private double r;
public Circle() { }
public Circle(double r)
{
this.r = r;
}
public double area()
{
return Math.PI*r*r;
}
public double length()
{
return 2 * Math.PI* r;
}
}
class Rect: IShape
{
private double w, h;
public Rect() { }
public Rect(double w, double h)
{
this.w = w; this.h = h;
}
public double area()
{
return w*h;
}
public double length()
{
return 2*(w+h);
}
}
例:定义一个会飞接口
interface ICanFly
{
void fly();
}
class Bird: ICanFly
{
public void fly()
{
Console.WriteLine("Bird Flying");
}
}
class Plane: ICanFly
{
public void fly()
{
Console.WriteLine("Plane Flying");
}
}
class Person
{
}
class Ex1_1
{
static void makeFly(Objectobj)
{
//Console.WriteLine(obj.GetType());
//Console.WriteLine(obj.ToString());
if (obj is ICanFly)
{
ICanFly fly = (ICanFly)obj;
fly.fly();
}
else
Console.WriteLine("Can not fly!");
}
static void Main(string[] args)
{
Bird bird = new Bird();
makeFly(bird);
Plane plane = new Plane();
makeFly(plane);
Person person = new Person();
makeFly(person);
Console.ReadLine();
}
}
本章练习题下载地址:点此下载
- C#学习笔记07:多态
- C# 学习笔记(Attribute) - 07
- C#学习笔记 ----C#变量
- C#学习笔记——多态
- C#学习笔记(2008-07-31)
- c#学习笔记(1)
- C#学习笔记
- C# 学习笔记
- C#学习笔记(一)
- C#学习笔记(二)
- C#学习笔记(三)
- c#学习笔记
- C#学习笔记
- C#学习笔记
- C#学习笔记
- c#深入学习笔记
- C#学习笔记(1)
- C#学习笔记之一
- go语言 Golang官网被墙解决办法
- WPF概要
- VC++在MFC程序中如何注册/注销ActiveX控件(.OCX)
- 2013-7-30-CSS 相对定位与绝对定位
- hdu1285确定比赛名次
- C#学习笔记07:多态
- 调整管
- 如何解决ie8 不支持new Date('2012-11-10')的问题
- 向全国推荐优秀古籍整理图书活动入选书目公示(zz)
- List结果集排序
- Ill-advised or mistaken usage of a core class (java.* or javax.*) Conversion to Dalvik format fail
- tomcat的URIEncoding的作用(转)
- 快速配置 Samba 将 Linux 目录映射为 Windows 驱动器,用于跨平台编程
- 使用reportlab生成中文表格pdf